简体   繁体   中英

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

在此处输入图片说明

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM