Core Text - select text in iPhone?

前端 未结 1 1484
陌清茗
陌清茗 2020-12-13 03:25

I need to render rich text using Core Text in my view (simple formatting, multiple fonts in one line of texts, etc.). I am wondering if text rendered this way can be selecte

相关标签:
1条回答
  • 2020-12-13 03:31

    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.

    selecting text drawn with CoreText

    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.

    0 讨论(0)
提交回复
热议问题