星期六, 2月 23, 2008

c# 計算字串的寬度

public static int CharWidth(string str, System.Drawing.Font font)
{
string target = str;
System.Windows.Forms.Control control = new System.Windows.Forms.Control();
System.Drawing.Graphics g = control.CreateGraphics();
System.Drawing.SizeF sizef = g.MeasureString(target, font);
g.Dispose(); // Necesary to destroy the graphics object
int charWidth = (int)sizef.Width; // gets the width of the size object.
return charWidth;
}

沒有留言: