c#(mobile) 绘制文字自动换行的实现
来源:互联网 发布:软件即服务 编辑:程序博客网 时间:2024/05/18 09:14
问题描述:写一个自定义的控件,在使用Graphics.DrawString()方法时发现.NET Compact Framework不支持自动换行。
问题解决:自己写了一个方法实现自动换行,主要实现了以下情况的换行:1.文本长度超过指定宽度2.文本中包含回车换行 符 。相关代码如下:
/// <summary>
/// 绘制文本自动换行(超出截断)
/// </summary>
/// <param name="graphic">绘图图面</param>
/// <param name="font">字体</param>
/// <param name="text">文本</param>
/// <param name="recangle">绘制范围</param>
private void DrawStringWrap(Graphics graphic, Font font, string text, Rectangle recangle)
{
List<string> 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[i], 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;
}
- c#(mobile) 绘制文字自动换行的实现
- c#(mobile) 绘制文字自动换行的实现
- DIV文字自动换行的实现
- DIV文字自动换行的实现
- android bitmap绘制文字自动换行
- android bitmap绘制文字自动换行
- 在区域内绘制宽字符串多行自动换行的c语言实现方法
- CSS实现文字自动换行
- canvas的文字自动换行
- J2ME开发中实现文字的自动换行
- css实现页面文字不换行、自动换行、强制换行
- HTML5 canvas 绘制的文字如何换行?
- 绘制在某个矩形区域内字符串自动多行换行的一个方法(c)语言实现
- CSS实现文字自动换行(兼容Firefox)
- CSS实现文字自动换行(兼容Firefox)
- android listView实现文字编辑自动换行
- CSS3实现文字阴影与自动换行
- JTable单元格文字实现自动换行
- 将数值转换为表示十进制数的字符串
- win64 debugging
- IIS音频驱动程序分析
- dom4j 操作xml
- linux 启动时“smartd”总是失败?
- c#(mobile) 绘制文字自动换行的实现
- operator=函数.
- 编译内核
- Qt4.5与VS2008/VS2005的集成开发环境的安装配置
- spring笔记
- gdb in Debian
- OA系统关于部门、组、人员权限组合的测试方法
- 编译安装3945驱动
- 从键盘输入文件结束符