Core Text - Get Pixel Coordinates from NSRange
Asked Answered
E

2

7

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

I am using Core Text with an NSAttributedString.

Ever answered 18/12, 2010 at 10:56 Comment(0)
G
10

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.

Gasiform answered 18/12, 2010 at 21:33 Comment(5)
A detailed answer, thanks very much! It's always a pain to find all the functions that are required for things such as this. :)Ever
@Ever can u share ur code when implementing this answer?? i think i have the some problem and can not solved it until 3 weeks, help me, please...Haleakala
@Risma I never actually got round to implementing this but everything you need is in Sean's answer.Ever
I'm trying to solve this problem at the moment, and I'm hung up at a certain point - I can't seem to get "string access" to the CTLineRef for the text. Any ideas? Here's my code: gist.github.com/bryanjclark/7036101Micronutrient
@Micronutrient did you ever find a solution to this, I'm struggling with similar issuesAilsun
H
2

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.

Hermineherminia answered 18/12, 2010 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.