最近遇到了一個須要手動爲顯示文字換行的場合,網上轉了一圈,最後造成了下面的代碼:spa
var font = new Font("微軟雅黑", 9F); var maxTextWidth = panel_detail.Width - 22 - DETAIL_BASE_INDENT - DETAIL_INDENT * level - 6; var graphic = panel_detail.CreateGraphics(); var textRemained = text; while (textRemained.Length > 0) { int characters, lines; graphic.MeasureString(textRemained, font, new SizeF(Convert.ToSingle(maxTextWidth), Convert.ToSingle(DETAIL_HEIGHT)), StringFormat.GenericTypographic, out characters, out lines); var currentTextLine = textRemained.Substring(0, characters); textRemained = textRemained.Substring(characters);
// TODO: 使用font做爲參數,將currentTextLine中的文字展現出來 }
需注意StringFormat一項最好不要設成new StringFormat(),不然獲得的計算結果和用Label展現時的大小差距很大。code