2

有没有办法对文本进行命中测试?例如,如果我在屏幕上的边界框中绘制文本“Hello graph!”,我如何知道这些空白矩形(空白区域)的尺寸和位置:

  • 字母“e”上方的空白矩形
  • 从字母“o”上方到字母“p”上方的空白矩形
  • 字母“H”下方的空白矩形直到“g”之前的空格

等等,你明白了。

换句话说,如何找出实际文本占用的区域以及真正空白的区域。

平台(图形库)是 Mac OS X 上的 Cocoa,字符集是 Unicode(这可能排除了原始 CoreGraphics API?),字体可以是 Cocoa 可以使用的任何东西。

提前致谢

4

2 回答 2

1

You could draw the text over fully-transparent bitmap (via CGBitmapContext), then check that bitmap if a particular point is transparent or not.

If you need a list of rectangles (that is called region in 2d graphics), you'll have to implement that yourself or google for a library, as CoreGraphics and Cocoa don't have regions (at least documented).

于 2011-08-15T06:52:36.130 回答
1

You can get the rect of a character in a NSTextView like this:

//Get the range of characters, which may be different than the range of glyphs
NSRange range = [[textView layoutManager]glyphRangeForCharacterRange:NSMakeRange(charIndex, 0) actualCharacterRange:NULL]

//Get the rect of the character
NSRect rect = [[textView layoutManager]boundingRectForGlyphRange:range inTextContainer:[textView textContainer]];

Then, get the NSGlyph that you want:

NSGlyph glyph = [[textView layoutManager]glyphAtIndex:range.location];

And draw it in an NSBezierPath:

NSBezierPath *path = [NSBezierPath bezierPath];
[path appendBezierPathWithGlyph:glyph inFont:myFavoriteFont];

Next, query the path for its bounds:

NSRect actualRect = [path bounds];

You can then compare those two rectangles.

Have a look at the NSLayoutManager Class Reference, the Text System Overview, and the Text Layout Programming Guide.

于 2011-08-15T06:28:09.630 回答