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...
解决方案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." MSDNUse 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));
}
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);