11

I am trying to add a text scale to a color image. The agcScale.jpg image (below) is 2 winform labels on the top and bottom and 2 winform pictureboxes on the left and right. The exact same code was used to produce the strings in the right and left pictureboxes, the only difference is that pictureBoxAgcVscale contains only the strings. Why does DrawString in pictureBoxAgc look fine but DrawString in pictureBoxAgcVscale look so bad? I can probably fix pictureBoxAgcVscale by doing a bmp.SetPixel for each pixel but that seems like the wrong way to fix this.

agcScale.jpg

private void DisplayAgcVscale(double min, double max)
{
    var bmp = new Bitmap(pictureBoxAgcVscale.Width, pictureBoxAgcVscale.Height);
    var c = (max - min) / bmp.Height;
    using (var g = Graphics.FromImage(bmp))
    {
        var font = new Font("Microsoft Sans Serif", 8.25F);
        var y1 = bmp.Height / 10;
        for (var y = y1; y < bmp.Height; y += y1)
        {
            var agc = y * c + min;
            var text = agc.ToString("#0.000V");
            var h = bmp.Height - y - font.Height / 2;
            g.DrawString(text, font, Brushes.Black, 0, h);
        }
    }
    pictureBoxAgcVscale.Image = bmp;
}
leppie
  • 115,091
  • 17
  • 196
  • 297
jacknad
  • 13,483
  • 40
  • 124
  • 194

2 Answers2

15

You are drawing black text on a transparent background. The anti-aliasing pixels are fading from black to black, no choice, turning the letters into blobs. It works for the text on the left because you draw the pixels first.

You forgot g.Clear().

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • `g.Clear` on a blank image? Have to try this now. – leppie Oct 25 '11 at 16:30
  • Thanks a million. g.Clear() works fine, but it was counter intuitive (to me) that `g.Clear()` is needed for a `transparent` background. – jacknad Oct 25 '11 at 21:29
  • Thanks..I resolve bad text quality with this idea of g.Clear().. I had to write text directly on image. g.Clear() helped me. In my case I could not use g.clear() directly on image loaded in Graphics object. First I create new empty bitmap, then I use g.Clear(), then I write text on this new bitmap and at the end I overlay this bitmap on original image. – t4taurus Jan 24 '17 at 21:07
0

I had a similar issue, but in a listbox, and it wasn't resolved by clearing the rectangle. I had to apply a "TextRenderingHint":

e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
e.Graphics.DrawString(listText, myFont, myBrush, e.Bounds, StringFormat.GenericDefault);
Dave
  • 3,093
  • 35
  • 32