开发者

Hit-testing text in Cocoa (Mac)?

Is there a way for hit-testing text? That is for example if I draw text "Hello graph!"" on the screen, within a bounding box, how can I tell the dimension and position of these blank rectangles (blank spaces):

  • The blank rectangle above the letter "e"
  • The blank rectangle that spans from above the letter "o" up to above the letter "p"
  • The blank rectangle below the letter "H" up to the space before "g"

etc, you get the idea.

In other words how to find out which areas occupied by actual text and which area开发者_如何学运维s that are really blank.

The platform (graphics library) is Cocoa on Mac OS X, the character set is Unicode (which probably rules out raw CoreGraphics API?), and the font can be anything that Cocoa can use.

Thanks in advance


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜