Why System.Drawing + ClearType font have ugly black fragments?

空扰寡人 提交于 2019-12-08 03:58:13

问题


I'm using following C# code to make a picture with a text in it

            // 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();

prior to this code, target.BackColor has been set into a desired color like

target.BackColor = Color.Black;

This is the results :


(source: free.in.th)

I was wondering that why ClearType font looks so ugly on bright bg? (On bg like dark purple you won't notice black border but it's still there)


回答1:


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

That's a problem, you haven't initialized the pixels of the bitmap. They'll default to Color.Transparent. Which causes text to be anti-aliased to black since Color.Transparent has red, green and blue at 0. When you then display the bitmap against a pink background, the anti-aliasing pixels become very visible since they weren't drawn to blend into a pink background. They only look good on a black background.

You'll need to use Graphics.Clear(). Or give up on anti-aliasing if the transparency was intended.



来源:https://stackoverflow.com/questions/7480150/why-system-drawing-cleartype-font-have-ugly-black-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!