Drawing white text with black background

I'm trying to add some text to my picutures before I display them on my website. To make sure the text can be read, I want to write the text in white letter on a black background.

At the moment, I first draw a black rectangle (using Graphics.DrawRectangle) and then I add the text in white (using Graphics.DrawString).

While this approach works, I always have to draw a large black rectangle to make sure it's large enough to fit the text in. If I have a a small string, it only fills up a small part of the rectangle, which doesn't look good

I'm sure there is an easy way to draw a string in a given color on a background of another color, so if someone could give me a push in the right direction...




Answer this question

Drawing white text with black background

  • Matty G

    Use Graphics.MeasureString() to determine the size of the text that is to be written before you draw your rectangle. This will help with the size issue.

    Also, you may want to tinker with adjusting the color of your text and background rectangle by setting the Alpha value of the color to some value less than 255. This produces a "transparency" effect - and may help improve the appearance of your text-over-image results.

    Sam Jones
    Adaptive Intelligence
    http://www.adaptiveintelligence.net



  • Kalyani Sundaresan

    Thanks a lot Sam,

    I'll definitely give the Alpha value thingy a try (i'm not a graphics expert, as you might have guessed )



  • Maxncl

    Acidentally stumbled upon the solution on the GotDotNet site (http://samples.gotdotnet.com/quickstart/winforms/doc/WinFormsGDIPlus.aspx) while I was looking for something else:-)

    The graphics class exposes the MeasureString method which you can use to calculate the width of a string

    string stringToDraw = "Some text";

    Font fnt = new Font("Verdana", 10, GraphicsUnit.Pixel);

    Brush brs = new SolidBrush (Color.White);

    System.Drawing.SizeF stringSize = graphics.MeasureString(stringToDraw, fnt);

    graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, stringSize.Width, stringSize.Height);

    graphics.DrawString(stringToDraw, fnt, brs, 0, 0);



  • Drawing white text with black background