问题
How would I get a CGRect
from an NSRange
for text rendered with Core Text?
I am using Core Text with an NSAttributedString
.
回答1:
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.
回答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.
来源:https://stackoverflow.com/questions/4477742/core-text-get-pixel-coordinates-from-nsrange