Home > Back-end >  Graphics.DrawString renders text with black outline on a transparent background
Graphics.DrawString renders text with black outline on a transparent background

Time:11-04

I'm drawing a string on a Bitmap with transparent background using Graphics.DrawString() and I get text with a black contour, when the Font size is smaller than 23 millimeters (the Font is created with GraphicsUnit.Millimeter).

Code:

Bitmap bmp = new Bitmap(2000, 2000);
Color alpha = Color.FromArgb(0, 0, 0, 0);
for (int x = 0; x < bmp.Width; x  )
   for (int y = 0; y < bmp.Height; y  )
      bmp.SetPixel(x, y, alpha);

Graphics g = Graphics.FromImage(bmp);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;

Font labelFont = new Font("Cascadia Mono SemiBold", 23/*22*/, FontStyle.Regular, GraphicsUnit.Millimeter);
Brush brush = new SolidBrush(Color.White);
g.DrawString("Some text", labelFont, brush, 200, 200);

23 Millimeters-Units font:
23mm Font

22 Millimeters-Units font: 23mm Font

I tried to use TextRenderer, but this draws text without transparent background.

CodePudding user response:

The code presented here has multiple problems:

  • The initial loop is counter-productive for multiple reasons:
    • Tries to fill a Bitmap with a transparent color, but this is already the non-color associated with a newly created Bitmap (Color.FromArb(0, 0, 0, 0))
    • Uses the SetPixel() method, the slowest possible tool for the task
      • If needed, a Bitmap can be filled with a Color using the TextRenderer.DrawText vs. Graphics.DrawString()

  • Related