C#正确获取像素中的字符串宽度 [英] C# Correctly Get String Width in Pixel
问题描述
大家好,
我正在为我开发新软件。但我有一点问题。当我想获得字符串宽度时,我已经使用了该代码;
float aa = pe.Graphics.MeasureString(PROGRAMMING,Font).Width ;
但这个值不正确。当我用该代码测试该行时;
pe.Graphics.DrawString(PROGRAMMING,Font,Brushes.White,new PointF(0,0) ));
float aa = pe.Graphics.MeasureString(PROGRAMMING,Font).Width;
pe.Graphics.DrawLine(new Pen(Brushes.CadetBlue, 4),新的PointF(0,1),新的PointF(aa,1));
此代码的结果;
https://social.msdn.microsoft.com/Forums/getfile/573128 [< a href =https://social.msdn.microsoft.com/Forums/getfile/573128\"target =_ blanktitle =New Window> ^ ]
线长总是出错。
如何解决这个问题?这对我的项目来说非常重要。我在等你的帮助。谢谢你的回答。祝你有个美好的一天...
Hi everyone,
I'm developing new software for me. But I have a little problem. When I wanna get the String Width, already I use that code;
float aa = pe.Graphics.MeasureString("PROGRAMMING", Font).Width;
But this value is not correct. When I test that line with that code;
pe.Graphics.DrawString("PROGRAMMING", Font, Brushes.White, new PointF(0, 0));
float aa = pe.Graphics.MeasureString("PROGRAMMING", Font).Width;
pe.Graphics.DrawLine(new Pen(Brushes.CadetBlue, 4), new PointF(0, 1), new PointF(aa, 1));
Result of this code;
https://social.msdn.microsoft.com/Forums/getfile/573128[^]
The Line length always going wrong.
How can I solve this problem? That's calculate very important for my project. I'm waiting for your helps. Thanks for all answer. Have a good day...
推荐答案
使用默认的'MeasureString和'DrawString:渲染字符串时,可以自动添加前导空格和尾随空格:
Using the default 'MeasureString and 'DrawString: leading-space and trailing-space may be automatically added when the string is rendered:
"The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString." MSDN
使用此处代码中显示的StringFormat可选参数之一来阻止该默认行为。
Use one of the StringFormat optional arguments as shown in the code here to block that default behavior.
Font font = new System.Drawing.Font("Arial", 16.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics pe = e.Graphics;
float aa = pe.MeasureString("PROGRAMMING", font,0,StringFormat.GenericTypographic).Width + 40;
pe.DrawString("PROGRAMMING", font, Brushes.White, new PointF(40, 40), StringFormat.GenericTypographic);
pe.DrawLine(new Pen(Brushes.CadetBlue, 4), new PointF(40, 40), new PointF(aa, 40));
}
尝试 TextRenderer.MeasureText方法 [ ^ ]
示例代码:
try with TextRenderer.MeasureText Method[^]
sample code :
String text1 = "Measure this text";
Font arialBold = new Font("Arial", 12.0F);
Size textSize = TextRenderer.MeasureText(text1, arialBold);
TextRenderer.DrawText(e.Graphics, text1, arialBold,
new Rectangle(new Point(10, 10), textSize), Color.Red);
这篇关于C#正确获取像素中的字符串宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!