Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone CoreText: Find the pixel coordinates of a substring

Here's a screenshot of the twitter app for reference: http://screencast.com/t/YmFmYmI4M

What I want to do is place a floating pop-over on top of a substring in an NSAttributedString that could span multiple lines. NSAttributedString is a requirement for the project.

In the screenshot supplied, you can see that links are background-highlighted, so it leads me to believe that they're using CoreText and NSAttributedStrings. I also found something called CTRunRef ( http://developer.apple.com/library/ios/#documentation/Carbon/Reference/CTRunRef/Reference/reference.html ) which looks promising, but I'm having trouble fitting it all together conceptually.

In short, if I have a paragraph in core text and when I tap on a word, how do I find the bounding box for that word?

like image 821
jtrim Avatar asked Sep 26 '10 00:09

jtrim


2 Answers

Set some attribute in the attributed string that won't effect display, but will cause it to be laid out as a seperate glyph run, then use CoreText to layout the string

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CTFrameRef ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);

Now you will have to hunt through the frame to find the relevant chunk of text. Get the array of CTLineRefs with CTFrameGetLines().

Iterate through the array, testing if the touch was on that line, by checking it is within the rect returned by CTLineGetImageBounds(). If it is, now look through the glyph runs in the line.

Again, you can get an array of CTRunRefs with CTLineGetGlyphRuns(). Check whether the tap was within the glyph run with CTRunGetImageBounds(), and if it was you can find the the range of indices in the original attributed string that the glyph run corresponds to with CTRunGetStringIndices().

like image 158
Hosiers Avatar answered Jan 05 '23 01:01

Hosiers


you need to find Y by CTLine and X by CTRun width and height you can get by word and font itself. ill attache my project link, its really simple code but you can reedit in order to meet your needs. hope it helps cheers if you improve general logic please let me know thx. textViewProject

like image 22
George Matiashvili Avatar answered Jan 04 '23 23:01

George Matiashvili