问题描述
我需要在视图中使用Core Text渲染富文本(简单格式化,一行文本中的多种字体等)。我想知道用户是否可以使用(标准复制/粘贴功能)选择以这种方式呈现的文本?
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 selected by user using (standard copy / paste function)?
推荐答案
我实现了CoreText中的文本选择。这真的是一项艰苦的工作......但它是可行的。
I implemented a text selection in CoreText. It is really a hard work... But it's doable.
基本上你必须使用 CTFrameGetLineOrigins $ c保存所有
CTLine
rects和origin $ c> , CTLineGetTypographicBounds
, CTLineGetStringRange
和 CTLineGetOffsetForStringIndex
。
Basically you have to save all CTLine
rects and origins using CTFrameGetLineOrigins
, CTLineGetTypographicBounds
, CTLineGetStringRange
and CTLineGetOffsetForStringIndex
.
行rect可以使用原点,ascent ,descent 和偏移,如下所示。
The line rect can be calculated using the origin, ascent, descent and offset as shown bellow.
lineRect = CGRectMake(origin.x + offset,
origin.y - descent,
offset,
ascent + descent);
执行此操作后,您可以测试哪条线有触摸点循环线(始终记住CoreText使用反Y坐标。
After doing that, you can test which line has the touched point looping the lines (always remember that CoreText uses inverse Y coordinates).
知道具有触摸点的线,您可以使用<$知道位于该点的字母(或最近的字母) c $ c> CTLineGetStringIndexForPosition 。
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
.
这是一个截图。
对于那个放大镜,我使用了代码在此帖中显示。
For that loupe, I used the code shown in this post.
编辑:
要绘制蓝色背景选择,您必须使用绘制矩形CGContextFillRect
。不幸的是, NSAttributedString
中没有背景颜色。
To draw the blue background selection, you have to paint the rect using CGContextFillRect
. Unfortunately, there's no background color in NSAttributedString
.
这篇关于核心文本 - 在iPhone中选择文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!