如何使用 .Net 在图像上写入具有特定背景颜色的文本 System.Drawing
How to write texts with a specific background color on images using .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);
}
如果唯一的选择是在我的文本下方画一个框,有没有办法知道所写文本的大小以及绘制它们的最佳方式是什么?
您可以使用
获取文本的大小
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);
}
}
我想在图片上写一些文字(用户绘制的形状旁边的某种自动标签),但是这些标签有时无法阅读,因为它们与背景图片重叠。我正在考虑用纯白色背景编写文本,但我不知道如何指定它。这是我当前的代码:
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);
}
}