【问题标题】:How to get the bounding box of text on the screen in c#?如何在c#中获取屏幕上的文本边界框?
【发布时间】:2010-10-05 13:04:24
【问题描述】:

在一个WinForms TextBox 控件中,如何获取在屏幕坐标中作为指定字符位置的文本的边界框?我知道相关文本的开始索引和结束索引,但是鉴于这两个值,我如何找到该文本的边界框?

要清楚...我知道如何获取控件本身的边界框。我需要 TextBox.Text 的子字符串的边界框。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    我玩过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();
    ...
    

    【讨论】:

    • 哇,马特……太棒了。谢谢!!
    【解决方案2】:

    也许,您可以使用Graphics.MeasureString。您可以使用 CreateGraphics 方法获取表单的图形对象。假设您必须在“Hello World”中找到“World”的边界框。所以首先测量“Hello”字符串 - 这会给你“Hello”的宽度,这反过来会告诉你左边的位置。然后测量实际单词以获得正确的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 2021-01-03
      相关资源
      最近更新 更多