Core Text - Get Pixel Coordinates from NSRange

2019-03-10 07:26发布

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

I am using Core Text with an NSAttributedString.

2条回答
乱世女痞
2楼-- · 2019-03-10 07:53

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.

查看更多
Lonely孤独者°
3楼-- · 2019-03-10 08:12

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.

查看更多
登录 后发表回答