如何使用 Graphics.DrawString 绘制完全单色的文本?

How to draw completely monocolor text with use of Graphics.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);

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

这是因为位图的背景是透明的黑色。画之前尽量弄成透明的白色:

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

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

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

但是它可能只会填满文本矩形。我不确定。或者用没有背景色的 TextRenderer.DrawText 重载重复我们上面的操作 (gfx.Clear(...))。

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

已解决:(将 textrenderinghints 与 drawstring 结合使用)

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