Kosmo零
Kosmo零

Reputation: 4151

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

enter image description here

I need text to be completely white. I tried different brushes like Brushes.White and etc, but all bad. What can I do? All text pixels must be white, just opacity can change.

Upvotes: 2

Views: 1945

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

This is because the background of the bitmap is a transparent black. Try to make it a transparent white before drawing:

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

Apparently this does not change anything. Use TextRenderer.DrawText instead. It allows you to specify a background color:

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

However it might just fill the text rectangle. I'm not sure. Or repeat what we have done above (gfx.Clear(...)) with an overload of TextRenderer.DrawText that does not have a backColor.

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

All these tricks just seem to have no effect at all. The only option left seems to be to disable anti-aliasing. This is done with SmoothingMode for non-text drawing (lines circles etc.) and TextRenderingHint for text rendering.

gfx.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; // For text
gfx.SmoothingMode = SmoothingMode.None; // For geometrical objects

Upvotes: 3

John
John

Reputation: 3702

Solved: (use the textrenderinghints in combination with 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);

Upvotes: 4

Related Questions