为什么System.Drawing + ClearType字体有丑陋的黑色片段?

时间:2011-09-20 04:28:47

标签: c# fonts system.drawing cleartype

我正在使用以下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;

结果如下:

http://image.free.in.th/z/ie/yqbsg.png

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

1 个答案:

答案 0 :(得分:7)

    else
    {
        result = new Bitmap(target.Width, target.Height);
    }

这是一个问题,你还没有初始化位图的像素。它们默认为Color.Transparent。由于Color.Transparent的红色,绿色和蓝色为0,因此将文本反锯齿变为黑色。当您在粉红色背景下显示位图时,抗锯齿像素变得非常明显,因为它们未被绘制为混合成粉红色的背景。它们在黑色背景上看起来很好。

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