在CATextLayer中显示属性字符串

时间:2013-04-17 06:14:27

标签: ios objective-c

我有一个简单的示例应用,我在其中创建CATextLayer并将其string属性设置为NSAttributedString。然后我将CATextLayer添加到视图中。

#import <CoreText/CoreText.h>
#import <QuartzCore/QuartzCore.h>

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    CTFontRef fontFace = CTFontCreateWithName((__bridge CFStringRef)(@"HelfaSemiBold"), 24.0, NULL);
    NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
    [attributes setObject:(__bridge id)fontFace forKey:(NSString*)kCTFontAttributeName];
    [attributes setObject:[UIColor blueColor] forKey:(NSString*)kCTForegroundColorAttributeName];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"Lorem Ipsum" attributes:attributes];

    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.backgroundColor = [UIColor whiteColor].CGColor;
    textLayer.frame = CGRectMake(20, 20, 200, 100);
    textLayer.contentsScale = [[UIScreen mainScreen] scale];
    textLayer.string = attrStr;

    [self.view.layer addSublayer:textLayer];
}

这在模拟器中效果很好,除了文本是黑色而不是蓝色。当在设备上运行时,一切都像在模拟器上一样显示,但它在控制台中产生以下两个错误。

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0

我应该在某处设置CGContext吗?我的属性设置错了吗?我完全走错了路。请注意,这适用于iOS 5.x应用程序,出于性能原因,我想使用CATextLayer。真正的应用程序将有许多 CATextLayer s。

2 个答案:

答案 0 :(得分:12)

您必须使用CGColor代替UIColor kCTForegroundColorAttributeName

[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
               forKey:(NSString *)kCTForegroundColorAttributeName];

答案 1 :(得分:0)

我将它转换为Swift 3并将其放入SpriteKit中:

import QuartzCore
import SpriteKit

class GameScene: SKScene {

  var textLayer = CATextLayer()

  func helloWord() {
    let fontFace = CTFontCreateWithName((("HelfaSemiBold") as CFString),
                                        24.0,
                                        nil)
    var attributes: [AnyHashable: Any]? = [:]
    attributes?[(kCTFontAttributeName as String)] = fontFace
    attributes?[(kCTForegroundColorAttributeName as String)] = UIColor.blue.cgColor

    let attrStr = NSAttributedString(string: "Hello Attributed Word!",
                                     attributes: attributes as! [String : Any]?)

    textLayer.backgroundColor = UIColor.white.cgColor
    textLayer.frame = CGRect(x: CGFloat(50), y: CGFloat(200),
                             width: CGFloat(300), height: CGFloat(100))
    textLayer.contentsScale = UIScreen.main.scale
    textLayer.string = attrStr
    self.view?.layer.addSublayer(textLayer)
  }

  override func didMove(to view: SKView) {
    helloWord()
  }
}