12

我计划使用 NSAttributedString 来突出显示与用户搜索匹配的字符串部分。但是,我找不到与 iOS 等效的NSBackgroundColorAttributeName—there's no kCTBackgroundColorAttributeName. 这样的事情是否存在,类似于变成的NSForegroundColorAttributeName方式kCTForegroundColorAttributeName

4

2 回答 2

8

不,Core Text 中不存在这样的属性,您必须在文本下方绘制自己的矩形来模拟它。

基本上,您必须弄清楚要为字符串中的给定范围填充哪些矩形。如果您使用CTFramesetter产生 a 的 a进行布局,则需要使用andCTFrame获取其线条及其来源。CTFrameGetLinesCTFrameGetLineOrigins

然后遍历这些行并使用CTLineGetStringRange它来找出哪些行是您要突出显示的范围的一部分。要填充矩形,请使用CTLineGetTypographicBounds(用于高度)和CTLineGetOffsetForStringIndex(用于水平偏移和宽度)。

于 2011-07-31T16:33:05.373 回答
4

NSBackgroundColorAttributeName 在 iOS 6 中可用,您可以通过以下方式使用它:

[_attributedText addAttribute: NSBackgroundColorAttributeName value:[UIColor yellowColor] range:textRange];

[_attributedText drawInRect:rect]; 

drawInRect:将支持 NSBackgroundColorAttributeName 和 iOS 6 支持的所有 NS*AttributeNames。

对于 CTFrameDraw(),不支持背景文本颜色。

代码:

- (void)drawRect:(CGRect)rect {    

    // First draw selection / marked text, then draw text

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    [_attributedText drawInRect:rect];

    CGContextRestoreGState(context);

//  CTFrameDraw(_frame, UIGraphicsGetCurrentContext());

}
于 2012-10-18T18:43:51.313 回答