【发布时间】:2010-10-05 13:04:24
【问题描述】:
在一个WinForms TextBox 控件中,如何获取在屏幕坐标中作为指定字符位置的文本的边界框?我知道相关文本的开始索引和结束索引,但是鉴于这两个值,我如何找到该文本的边界框?
要清楚...我知道如何获取控件本身的边界框。我需要 TextBox.Text 的子字符串的边界框。
【问题讨论】:
在一个WinForms TextBox 控件中,如何获取在屏幕坐标中作为指定字符位置的文本的边界框?我知道相关文本的开始索引和结束索引,但是鉴于这两个值,我如何找到该文本的边界框?
要清楚...我知道如何获取控件本身的边界框。我需要 TextBox.Text 的子字符串的边界框。
【问题讨论】:
我玩过Graphics.MeasureString,但无法获得准确的结果。以下代码使用Graphics.MeasureCharacterRanges 为我提供了不同字体大小的相当一致的结果。
private Rectangle GetTextBounds(TextBox textBox, int startPosition, int length)
{
using (Graphics g = textBox.CreateGraphics())
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
CharacterRange[] characterRanges = { new CharacterRange(startPosition, length) };
StringFormat stringFormat = new StringFormat(StringFormat.GenericTypographic);
stringFormat.SetMeasurableCharacterRanges(characterRanges);
Region region = g.MeasureCharacterRanges(textBox.Text, textBox.Font,
textBox.Bounds, stringFormat)[0];
Rectangle bounds = Rectangle.Round(region.GetBounds(g));
Point textOffset = textBox.GetPositionFromCharIndex(0);
return new Rectangle(textBox.Margin.Left + bounds.Left + textOffset.X,
textBox.Margin.Top + textBox.Location.Y + textOffset.Y,
bounds.Width, bounds.Height);
}
}
这个 sn-p 只是在我的 TextBox 顶部放置一个面板来说明计算出的矩形。
...
Rectangle r = GetTextBounds(textBox1, 2, 10);
Panel panel = new Panel
{
Bounds = r,
BorderStyle = BorderStyle.FixedSingle,
};
this.Controls.Add(panel);
panel.Show();
panel.BringToFront();
...
【讨论】:
也许,您可以使用Graphics.MeasureString。您可以使用 CreateGraphics 方法获取表单的图形对象。假设您必须在“Hello World”中找到“World”的边界框。所以首先测量“Hello”字符串 - 这会给你“Hello”的宽度,这反过来会告诉你左边的位置。然后测量实际单词以获得正确的位置。
【讨论】: