如何使用Graphics.DrawString绘制完全monocolor文本?

时间:2015-01-03 21:27:34

标签: c# string graphics colors drawstring

Bitmap bmp = new Bitmap(300, 50);
Graphics gfx = Graphics.FromImage(bmp);
gfx.DrawString("Why I have black outer pixels?", new Font("Verdana", 14),
    new SolidBrush(Color.White), 0, 0);
gfx.Dispose();
bmp.Save(Application.StartupPath + "\\test.png", ImageFormat.Png);

enter image description here

我需要文字完全是白色的。我尝试了不同的画笔,如Brushes.White等,但都很糟糕。我能做什么?所有文本像素必须为白色,只是不透明度可以更改。

2 个答案:

答案 0 :(得分:3)

解决:(使用textrenderinghints与抽绳结合使用)

        Bitmap bmp = new Bitmap(300, 50);
        Graphics gfx = Graphics.FromImage(bmp);

        gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        gfx.DrawString("Why I have black outer pixels?", new Font("Verdana", 14),
            new SolidBrush(Color.White), 0, 0);
        gfx.Dispose();
        bmp.Save(Application.StartupPath + "\\test.png", ImageFormat.Png);

答案 1 :(得分:1)

这是因为位图的背景是透明的黑色。在绘制之前尝试使其成为透明白色:

gfx.Clear(Color.FromArgb(0, 255, 255, 255));

显然这不会改变任何事情。请改用TextRenderer.DrawText。它允许您指定背景颜色:

TextRenderer.DrawText(gfx, "text", font, point, foreColor, backColor);

但是它可能只填充文本矩形。我不确定。或者重复上面的操作(gfx.Clear(...)),重载为TextRenderer.DrawText,但没有backColor。

gfx.Clear(Color.FromArgb(1, 255, 255, 255));
TextRenderer.DrawText(gfx, "text", font, point, Color.White)

所有这些技巧似乎都没有任何效果。剩下的唯一选择似乎是禁用抗锯齿。这是通过SmoothingMode进行非文字绘制(线条圆圈等)和TextRenderingHint进行文字渲染。

gfx.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; // For text
gfx.SmoothingMode = SmoothingMode.None; // For geometrical objects
相关问题