怎么用MeasureCharacterRanges测量文本范围,得到的范围不正确?
如下代码所示:
private void panel2_Paint(object sender, PaintEventArgs e)
{
string text = "panel1_Paint ";
Font font = new Font(this.Font.FontFamily, 22);
StringFormat format = StringFormat.GenericTypographic;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
CharacterRange[] ranges ={ new CharacterRange(0, text.Length) };
format.SetMeasurableCharacterRanges(ranges);
Region[] region = e.Graphics.MeasureCharacterRanges(text, font, new RectangleF(10, 10, int.MaxValue, int.MaxValue), format);
Rectangle rect = Rectangle.Round(region[0].GetBounds(e.Graphics));
e.Graphics.DrawString(text, font, Brushes.Red, rect, format);
e.Graphics.DrawRectangle(Pens.Blue, rect);
}
这段代码用来测试和绘制英文是没有问题的,可是如果测量和绘制的文本中含有中文字符的话,就不正确了。如:
private void panel2_Paint(object sender, PaintEventArgs e)
{
string text = "panel1_Paint宋体 ";
Font font = new Font(this.Font.FontFamily, 22);
StringFormat format = StringFormat.GenericTypographic;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
CharacterRange[] ranges ={ new CharacterRange(0, text.Length) };
format.SetMeasurableCharacterRanges(ranges);
Region[] region = e.Graphics.MeasureCharacterRanges(text, font, new RectangleF(10, 10, int.MaxValue, int.MaxValue), format);
Rectangle rect = Rectangle.Round(region[0].GetBounds(e.Graphics));
e.Graphics.DrawString(text, font, Brushes.Red, rect, format);
e.Graphics.DrawRectangle(Pens.Blue, rect);
}
这样的话,绘制出来的文本总是缺少最后一个文字。请问怎么才能解决这个问题,万分感谢!
------解决方案--------------------CharacterRange[] ranges ={ new CharacterRange(0, text.Length) };
这里 一个汉字 应该是2个字符
text.Length这样取只按照英文一样
当然 总长少了一个汉字的位置肯定就没有了
用下面的函数 取字符 长度
/// <summary>
/// 检测含有中文字符串的实际长度
/// </summary>
/// <param name= "str "> 字符串 </param>
public static int cnLenth(string str)
{
System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();
byte[] b = n.GetBytes(str);
int l = 0; // l 为字符串之实际长度
for (int i = 0; i <= b.Length - 1; i++)
{
if (b[i] == 63) //判断是否为汉字或全脚符号
{
l++;
}
l++;
}
return l;
}