简体   繁体   English

核心文本 - 从NSRange获取像素坐标

[英]Core Text - Get Pixel Coordinates from NSRange

How would I get a CGRect from an NSRange for text rendered with Core Text? 我将如何得到CGRectNSRange与核心文本呈现的文本?

I am using Core Text with an NSAttributedString . 我正在使用带有NSAttributedString Core Text。

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). 你需要让所有的帧使用线CTFrameGetLines()检查他们的字符范围是你要找的使用范围CTLineGetStringRange()使用CTLineGetTypographicBounds()找到多大的线本身就呈现为,并使用CTLineGetOffsetForStringIndex()来确定范围的开始/结束字符的实际位置(如果该行只是所需范围的子范围)。

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. 请注意, CTLineGetImageBounds()在没有图形上下文的情况下不起作用(而且,从我收集的内容来看,它无论如何都非常昂贵)并且不一定要解决这个问题。

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. 然后调用CTLineGetOffsetForStringIndex()以从行的开头获取特定字符串位置的偏移量。 Together with CTLineGetImageBounds() , it should be possible to calculate a CGPoint position of the first and last characters in your range. CTLineGetImageBounds()一起,应该可以计算范围中第一个和最后一个字符的CGPoint位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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