Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing text to a Bitmap with TextRenderer

I am trying to draw some text using TextRenderer (since this is favorable to using Graphics.DrawString) to a Bitmap, however it is having some very undesirable effects.

Example Code

using (Bitmap buffer = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
    using (Graphics graphics = Graphics.FromImage(buffer))
    {
        // Produces the result below
        graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
        // Produces clean text, but I'd really like ClearType!
        graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
        TextRenderer.DrawText(graphics, "Hello World", this.Font, this.ClientRectangle, Color.Black);
    }
    e.Graphics.DrawImageUnscaled(buffer, this.ClientRectangle);
}

Result

enter image description here

I'm not sure exactly how to fix this...help!

I do NOT want to use Graphics.DrawString as I want correct GDI (as opposed to GDI+) rendering.

NOTE: I've just realized, I've left a gaping hole in this question. Some people have pointed out that rendering ClearType text is working fine on their machines...

I'm trying to render the text to a transparent (Color.Transparent) bitmap. If I do it with a solid color, everything works fine! (but it is imperative that I render to a transparent Bitmap).

like image 716
Matthew Layton Avatar asked Sep 16 '13 22:09

Matthew Layton


1 Answers

Specify a BackColor in your call to DrawText():

TextRenderer.DrawText(graphics, "Hello World", this.Font, this.ClientRectangle, Color.Black, this.BackColor);
like image 129
Idle_Mind Avatar answered Sep 30 '22 14:09

Idle_Mind