关于计算文字显示占用画面大小(System.Drawing.Graphics.MeasureString)

最近遇到了一个须要手动为显示文字换行的场合,网上转了一圈,最后造成了下面的代码: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

相关文章
相关标签/搜索