【问题标题】:Why System.Drawing + ClearType font have ugly black fragments?为什么 System.Drawing + ClearType 字体有难看的黑色碎片?
【发布时间】:2011-11-20 18:19:33
【问题描述】:

我正在使用以下 C# 代码制作一张带有文字的图片

            // Create font. Parameter is a global variable
        Font objFont = new Font(fontname, fontsize, fontstyle, System.Drawing.GraphicsUnit.Pixel);

        // Grab an existing image from picture box. (target is picturebox's name)
        Bitmap result;
        if (target.Image != null)
        {
            result = new Bitmap(target.Image);
        }
        else
        {
            result = new Bitmap(target.Width, target.Height);
        }
        Graphics objGraphics = Graphics.FromImage(result);

        // And draw to it. Select a mode with check box.

        objGraphics.SmoothingMode = SmoothingMode.HighQuality;
        if (!checkBox1.Checked)
        {
            objGraphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
        }
        else
        {
            objGraphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
        }
        Brush b = new LinearGradientBrush(new Rectangle(new Point(x, y), objGraphics.MeasureString(text, objFont).ToSize()),color1,color2,LinearGradientMode.Vertical);

        objGraphics.DrawString(text, objFont, b, x, y);
        objGraphics.Save();
        
        //Set the result to picturebox

        target.Image = result;

        objGraphics.Dispose();
        b.Dispose();

在此代码之前,target.BackColor 已设置为所需的颜色,例如

target.BackColor = Color.Black;

这是结果:


(来源:free.in.th

我想知道为什么 ClearType 字体在明亮的背景上看起来如此丑陋? (在像深紫色这样的背景上,您不会注意到黑色边框,但它仍然存在)

【问题讨论】:

  • GDI 和 ClearType 在 WinForms 应用程序中不能很好地混合(假设您使用的是 WinForms,因为它是 System.Drawing)。

标签: c# fonts system.drawing cleartype


【解决方案1】:
    else
    {
        result = new Bitmap(target.Width, target.Height);
    }

这是个问题,你还没有初始化位图的像素。它们将默认为 Color.Transparent。这会导致文本被抗锯齿为黑色,因为 Color.Transparent 在 0 处具有红色、绿色和蓝色。当您在粉红色背景下显示位图时,抗锯齿像素变得非常明显,因为它们没有被绘制为混合变成粉红色的背景。它们只在黑色背景下看起来不错。

您需要使用 Graphics.Clear()。或者如果想要透明度,就放弃抗锯齿。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2022-01-22
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多