2009年9月18日 星期五

C#獲得繪圖字串的寬度

在繪圖字串時,因為TrueType的關係,在畫面上每個字的寬度會呈現不一樣的寬度。如果自己要對畫面上版面作控制,很容易無法掌握到寬度。

網路上有人針對這問題提出解答。就是利用MeasureString這個類別來完成。MeasureString能夠回傳相近似的寬度值,下面這些範例可以幫助理解。如果需要比較精確的值,那麼你應該使用Graphic.MeasureCharacterRamges。以下是範例程式。

Graphics g = e.Graphics;
string s1 = "init";
string s2 = "wimp";
string s3 = "initwimp";
StringFormat format = new StringFormat();
format.SetMeasurableCharacterRanges(new CharacterRange[]{new
CharacterRange(0, s1.Length)});
Region[] r = g.MeasureCharacterRanges(s1, this.Font, new Rectangle(0, 0,
1000, 1000), format);
RectangleF rect = r[0].GetBounds(g);
// using MeasureCharacterRanges
g.DrawString(s1, this.Font, SystemBrushes.ControlText, 0, 0);
g.DrawString(s2, this.Font, SystemBrushes.ControlText, rect.Width, 0);
// the assmbled string
g.DrawString(s3, this.Font, SystemBrushes.ControlText, 0, 20);
// using MeasureString
SizeF sf = g.MeasureString(s1, this.Font);
g.DrawString(s1, this.Font, SystemBrushes.ControlText, 0, 40);
g.DrawString(s2, this.Font, SystemBrushes.ControlText, sf.Width, 40);

參考資料及程式碼來源:
[1] Get actual text width.

沒有留言: