首页 > 技术文章 > c#使用字符串的像素大小来绘制文本

gougou1981 2020-06-15 17:09 原文

遇到的问题如下:

代码:
System.Drawing.Image imgBack = System.Drawing.Image.FromFile(sourceImg); //背景图片 System.Drawing.Image img = System.Drawing.Image.FromFile(destImg); //二维码图片 float fontSize = 12.0f;             //字体大小 Font font = new Font("宋体", fontSize);   //定义字体 int lineHeight = 30;//行高 float rectX = 300;//x坐标 float firstLineRectY = 800;//首行Y坐标 Graphics g = Graphics.FromImage(imgBack); g.DrawImage(img, 850, 850, 300, 300);             //float textWidth = textCompanyName.Length * fontSize; //文本的长度 float rectY = firstLineRectY;//300; float rectWidth = textCompanyName.Length * (fontSize + 8); float rectHeight = fontSize + 8; RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);             Brush whiteBrush = new SolidBrush(Color.Black);//黑笔刷,画文字用 g.DrawString(textCompanyName, font, whiteBrush, textArea);

 

使用Graphics绘制的文字如下,出现了错位,缺失的问题。

 

问题的生产原因主要是由于背景图像是300DPI,代码中Font默认的分辨率为72像素,如果背景底图为72像素就不会有问题(如下使用72DPI背景图片绘制的是正常的)

 

 

字体通常以点为单位,其中1点=1/72英寸。因此,10pt字体在每个屏幕分辨率上的大小(英寸)都是相同的,并且将根据屏幕分辨率和像素密度占用更多或更少的像素。以像素为单位测量的所有内容(如线条、形状等)都不会受到DPI的影响,但实际物理大小将根据屏幕分辨率和像素密度而变化。将代码更改为以像素为单位测量字体确实可以确保所有屏幕DPI设置中的文本都是相同的像素大小

 所以我们的代码使用以下方式来绘制文字:

// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);//测量用指定的 Font 绘制的指定字符串

// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));

参考文章:

https://www.cnblogs.com/goto/archive/2012/09/11/2680213.html

https://stackoverflow.com/questions/10800264/windows-dpi-setting-affects-graphics-drawstring

 

推荐阅读