Search code examples
.netsystem.drawing

How to write texts with a specific background color on images using .Net System.Drawing


I'd like to write some text over an image (some kind of automatic label aside shapes drawn by users) however these labels are sometimes not readable as they overlap with the background images. I was thinking to write texts with a solid white background color but I don't know how to specify it. Here is my current code:

var font =  new Font("Time New Roman", 20, GraphicsUnit.Pixel);

using (var brush = new SolidBrush(Color.Black))
using (var graphics = Graphics.FromImage(image))
{
    var position = new Point(10,10);
    graphics.DrawString("Hello", font, brush, position);
}

If the only option is to draw a box under my text, is there a way to know the size of the written text and what is the best way to draw them?


Solution

  • You can get the size of the text using

    var stringSize = graphics.MeasureString(text, _font);
    

    Try this.

    class Program
        {
            static Font _font = new Font("Time New Roman", 20, GraphicsUnit.Pixel);
            static SolidBrush _backgroundBrush = new SolidBrush(Color.White);
            static SolidBrush _textBrush = new SolidBrush(Color.Black);
    
            static void Main(string[] args)
            {
                using (var image = Image.FromFile(@"<some image location>\image.bmp"))
                using(var graphics = Graphics.FromImage(image))
                {
                    DrawLabel(graphics, new Point(10, 10), "test");
                    image.Save(@"<some image location>\image.bmp");         
                }
            }
    
            static void DrawLabel(Graphics graphics, Point labelLocation, string text)
            {            
                var stringSize = graphics.MeasureString(text, _font);
                var rectangle = new Rectangle(labelLocation, Size.Round(stringSize));
    
                graphics.FillRectangle(_backgroundBrush, rectangle);
                graphics.DrawString(text, _font, _textBrush, labelLocation);
            }
        }