我想在图像上写一些文本(某种自动标签,由用户绘制形状),但是这些标签有时是不可读的,因为它们与背景图像重叠。我正在考虑用纯白的背景色写文字,但我不知道该怎么写。以下是我的当前代码:
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);
}如果唯一的选择是在我的文字下面画一个方框,有没有办法知道文字的大小,以及画它们的最佳方法是什么?
发布于 2018-10-23 04:35:30
您可以使用
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);
}
}https://stackoverflow.com/questions/52924738
复制相似问题