Frage

After completing the following code the value of "result1" and "result2" variables (measured width of string) are the same, despite the fact that the "font1" is regular and the "font2" is bold. Interestingly, this error appears for the font "Times New Roman" and "Arial". For example for font "Calibri" returned values ​​are correct, the value of the variable "result2" is greater than the value of the variable "result1". Why is this happening?

using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
{
    graphics.PageUnit = System.Drawing.GraphicsUnit.Pixel;
    graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    System.Drawing.Font font1 = new System.Drawing.Font("Arial", 10.0f, System.Drawing.FontStyle.Regular);
    System.Drawing.Font font2 = new System.Drawing.Font("Arial", 10.0f, System.Drawing.FontStyle.Bold);
    float result1 = graphics.MeasureString("WWW", font1, int.MaxValue, System.Drawing.StringFormat.GenericTypographic).Width;
    float result2 = graphics.MeasureString("WWW", font2, int.MaxValue, System.Drawing.StringFormat.GenericTypographic).Width;
}
War es hilfreich?

Lösung

I just tried it with different strings and the width does change. I think it just so happens that "WWW" has the same length with/without the bold style. Just try it in an editor and you'll see it's the same size.

Andere Tipps

Actually draw it in the OnPaint() method and you'll see why:

enter image description here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top