简体   繁体   中英

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM