最近遇到了一个需要手动为显示文字换行的场合,网上转了一圈,最后形成了下面的代码:
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展示时的大小差距很大。