Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Text - Get Pixel Coordinates from NSRange

How would I get a CGRect from an NSRange for text rendered with Core Text?

I am using Core Text with an NSAttributedString.

like image 473
Joshua Avatar asked Dec 18 '10 10:12

Joshua


2 Answers

It is an absolute pain but can be done.

You need to get all of the lines in the frame using CTFrameGetLines(), check if their character range is in the range you're looking for using CTLineGetStringRange(), use CTLineGetTypographicBounds() to find how big the line itself would render as, and use CTLineGetOffsetForStringIndex() to determine the actual position of the start/end character of the range (if the line is just a subrange of the desired range).

Combining all of this and adding up offsets and heights and such can get you what you want. Note that CTLineGetImageBounds() doesn't work without a graphics context (and, from what I gather, it is pretty expensive anyway) and is not necessary to solve this problem.

like image 173
Sean Avatar answered Nov 17 '22 03:11

Sean


FIrst determine the line(s) in which the range you are interested in lies is. Then call CTLineGetOffsetForStringIndex() to get an offset of a specific string position from the start of the line. Together with CTLineGetImageBounds(), it should be possible to calculate a CGPoint position of the first and last characters in your range.

like image 2
Ole Begemann Avatar answered Nov 17 '22 05:11

Ole Begemann