Graphics graphics = CreateGraphics ();
SizeF SizeF = Graphics. MeasureString (TextBox1.Text, New Font ("Arial", 9));
MessageBox.Show (String. Format ("font width: {0}, Height: {1}", Sizef.width, Sizef.height));
Graphics. Dispose ();
Use G. MeasureString () obtained
The width of the characters measured with measurestring is always larger than the actual width, and as the length of the character increases, the gap between the actual width and the width of the measurement is increasing. Check out MSDN and find the following reason:
measurestring The method is intended to be used with an individual string, which includes a small amount of extra space before and after the string for the highlighted glyph.
String str;
str = "large";
Font f = new Font ("SimSun", 7F, System.Drawing.FontStyle.Regular);
Graphics g = this. CreateGraphics ();
Unit is mm
G.pageunit = Graphicsunit.millimeter;
SizeF sim = g.measurestring (str, f);
2. Obtained using Textrenderer.measuretext, provides the dimensions (in pixels) of the specified text drawn using the specified device context, font, and formatting instructions when creating the initial text border with the specified dimensions.
private void Measuretext (PaintEventArgs e)
{
string str;
str = "good everyone";
font f = new Font ("SimSun", 7F, System.Drawing.FontStyle.Regular);
size sif = TextRenderer.MeasureText (E . Graphics, str, F, new Size (0, 0), textformatflags.nopadding);
messagebox.show (SIF. WIDTH/PDI). ToString ());
}
private void Print (object sender, PaintEventArgs e)
{
Measuretext (e);
}
C # Get the pixel width of text