【问题标题】:NSBackgroundColorAttributeName-like attribute in NSAttributedString on iOS?iOS 上 NSAttributedString 中的 NSBackgroundColorAttributeName 类属性?
【发布时间】:2011-10-06 04:18:48
【问题描述】:

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

【问题讨论】:

标签: objective-c ios core-text nsattributedstring


【解决方案1】:

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

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

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

【讨论】:

  • 很好的答案。可惜没有一个简单的属性来替换所有代码。
  • 我的 DTCoreText 项目支持高亮显示,就像在 Mac 上一样。您有一个 NSAttributedString initWithHTMLData 方法来获取表单 HTML 到属性字符串和一个视图类,该类可以正确显示属性字符串,并在 CATextLayer 上具有许多附加功能。
【解决方案2】:

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());

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2011-08-11
    • 1970-01-01
    • 2023-04-09
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多