iOS上的NSAttributedString中的NSBackgroundColorAttributeName-like属性? [英] NSBackgroundColorAttributeName-like attribute in NSAttributedString on iOS?
问题描述
我计划使用NSAttributedString来突出显示用户搜索的匹配查询的字符串部分。但是,我找不到iOS等效的 NSBackgroundColorAttributeName
- 没有 kCTBackgroundColorAttributeName
。这样的事情是否存在,类似于 NSForegroundColorAttributeName
成为 kCTForegroundColorAttributeName
的方式?
I was planning on using NSAttributedString to highlight portions of strings with the matching query of a user's search. However, I can't find an iOS equivalent of NSBackgroundColorAttributeName
—there's no kCTBackgroundColorAttributeName
. Does such a thing exist, similar to the way NSForegroundColorAttributeName
becomes kCTForegroundColorAttributeName
?
推荐答案
不,Core Text中不存在这样的属性,你必须在文本下方绘制自己的矩形来模拟它。
No, such an attribute doesn't exist in Core Text, you'll have to draw your own rectangles underneath the text to simulate it.
基本上,你必须弄清楚要为字符串中的给定范围填充哪个矩形。如果使用产生 CTFrame
的 CTFramesetter
进行布局,则需要使用<获取其线条及其来源 CTFrameGetLines
和 CTFrameGetLineOrigins
。
Basically, you'll have to figure out which rectangle(s) to fill for a given range in the string. If you do your layout with a CTFramesetter
that produces a CTFrame
, you need to get its lines and their origins using CTFrameGetLines
and CTFrameGetLineOrigins
.
然后遍历行和使用 CTLineGetStringRange
找出哪些行是您要突出显示的范围的一部分。要获取矩形,请使用 CTLineGetTypographicBounds
(对于高度)和 CTLineGetOffsetForStringIndex
(对于水平偏移和宽度) 。
Then iterate over the lines and use CTLineGetStringRange
to find out which lines are part of the range you want to highlight. To get the rectangles to fill, use CTLineGetTypographicBounds
(for the height) and CTLineGetOffsetForStringIndex
(for the horizontal offset and width).
这篇关于iOS上的NSAttributedString中的NSBackgroundColorAttributeName-like属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!