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

如何使用.Net System.Drawing在图像上使用特定背景色编写文本,.net,system.drawing,.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 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);
}

如果唯一的选择是在“我的文字”下绘制一个方框,有没有办法知道书面文字的大小以及绘制它们的最佳方式?

您可以使用

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);
        }
    }
类程序
{
静态字体_Font=新字体(“TimeNewRoman”,20,GraphicsUnit.Pixel);
静态SolidBrush\u backgroundBrush=新的SolidBrush(颜色为白色);
静态SolidBrush _textBrush=新的SolidBrush(颜色为黑色);
静态void Main(字符串[]参数)
{
使用(var image=image.FromFile(@“\image.bmp”))
使用(var graphics=graphics.FromImage(image))
{
DrawLabel(图形,新点(10,10),“测试”);
image.Save(@“\image.bmp”);
}
}
静态空心DrawLabel(图形、点标签位置、字符串文本)
{            
var stringSize=graphics.MeasureString(文本,字体);
var rectangle=新矩形(标签位置,大小.圆形(stringSize));
图形.圆角矩形(_backgroundBrush,矩形);
绘图字符串(文本、字体、画笔、标签位置);
}
}