如何使用.Net System.Drawing在图像上写入具有特定背景色的文本

时间:2018-10-22 08:01:30

标签: .net system.drawing

我想在图像上写一些文本(除了用户绘制的某种自动标签形状),但是这些标签有时会不可读,因为它们与背景图像重叠。我当时想写纯白色背景的文本,但我不知道如何指定它。这是我当前的代码:

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);
}

如果唯一的选择是在我的文字下方画一个方框,是否有办法知道书面文字的大小,以及绘制文字的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用

获得文本的大小
var stringSize = graphics.MeasureString(text, _font);

尝试一下。

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);
        }
    }