Core Text - select text in iPhone?

最后都变了- 提交于 2019-11-28 17:07:24

I implemented a text selection in CoreText. It is really a hard work... But it's doable.

Basically you have to save all CTLine rects and origins using CTFrameGetLineOrigins(1), CTLineGetTypographicBounds(2), CTLineGetStringRange(3) and CTLineGetOffsetForStringIndex(4).

The line rect can be calculated using the origin(1), ascent(2), descent(2) and offset(3)(4) as shown bellow.

lineRect = CGRectMake(origin.x + offset, 
                      origin.y - descent, 
                      offset, 
                      ascent + descent);

After doing that, you can test which line has the touched point looping the lines (always remember that CoreText uses inverse Y coordinates).

Knowing the line that has the touched point, you can know the letter that is located at that point (or the nearest letter) using CTLineGetStringIndexForPosition.

Here's one screenshot.

For that loupe, I used the code shown in this post.

Edit: To draw the blue background selection, you have to paint the rect using CGContextFillRect. Unfortunately, there's no background color in NSAttributedString.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!