c#使用字符串的像素大小來繪制文本


遇到的問題如下:

代碼:
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM