【问题标题】:How to write texts with a specific background color on images using .Net System.Drawing如何使用 .Net System.Drawing 在图像上编写具有特定背景颜色的文本
【发布时间】:2019-03-26 06:09:32
【问题描述】:

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

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

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

【问题讨论】:

    标签: .net system.drawing


    【解决方案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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-26
      • 2016-06-25
      • 2014-06-04
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      相关资源
      最近更新 更多