c#(mobile) 绘制文字自动换行的实现

问题描述:写一个自定义的控件,在使用Graphics.DrawString()方法时发现.NET Compact Framework不支持自动换行。
问题解决:自己写了一个方法实现自动换行,主要实现了以下情况的换行:1.文本长度超过指定宽度2.文本中包含回车换行 符 。相关代码如下:
///
/// 绘制文本自动换行(超出截断)
///
/// 绘图图面
/// 字体
/// 文本
/// 绘制范围
private void DrawStringWrap(Graphics graphic, Font font, string text, Rectangle recangle)
{
List textRows = GetStringRows(graphic, font, text, recangle.Width);
int rowHeight = (int)(Math.Ceiling(graphic.MeasureString(\”测试\”, font).Height));

        int maxRowCount = recangle.Height / rowHeight;
        int drawRowCount = (maxRowCount < textRows.Count) ? maxRowCount : textRows.Count;

        int top = (recangle.Height - rowHeight * drawRowCount) / 2;

        StringFormat sf = new StringFormat();
        sf.Alignment = StringAlignment.Near;
        sf.LineAlignment = StringAlignment.Center;

        for (int i = 0; i < drawRowCount; i++)
        {
            Rectangle fontRectanle = new Rectangle(recangle.Left, top + rowHeight * i, recangle.Width, rowHeight);
            graphic.DrawString(textRows, font, new SolidBrush(Color.Black), fontRectanle, sf);
        }

    }

    /// <summary>
    /// 将文本分行
    /// </summary>
    /// <param name=\"graphic\">绘图图面</param>
    /// <param name=\"font\">字体</param>
    /// <param name=\"text\">文本</param>
    /// <param name=\"width\">行宽</param>
    /// <returns></returns>
    private List<string> GetStringRows(Graphics graphic, Font font, string text, int width)
    {
        int RowBeginIndex = 0;
        int rowEndIndex = 0;
        int textLength = text.Length;
        List<string> textRows = new List<string>();

        for (int index = 0; index < textLength; index++)
        {
            rowEndIndex = index;

            if (index == textLength - 1)
            {
                textRows.Add(text.Substring(RowBeginIndex));
            }
            else if (rowEndIndex + 1 < text.Length && text.Substring(rowEndIndex, 2) == \"\\r\\n\")
            {
                textRows.Add(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex));
                rowEndIndex=index += 2;
                RowBeginIndex = rowEndIndex;
            }
            else if (graphic.MeasureString(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex + 1), font).Width > width)
            {
                textRows.Add(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex));
                RowBeginIndex = rowEndIndex;
            }
        }

        return textRows;
    }
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值