在CATextLayer中显示属性字符串

Mic*_*ton 9 objective-c ios

我有一个简单的示例应用程序,我创建一个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];
}
Run Code Online (Sandbox Code Playgroud)

这在模拟器中很有效,除了文本是黑色而不是蓝色.在设备上运行时,所有内容都显示在模拟器上,但它会在控制台中生成以下两个错误.

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Run Code Online (Sandbox Code Playgroud)

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

Vit*_*erg 12

您必须使用CGColor的,而不是UIColorkCTForegroundColorAttributeName:

[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
               forKey:(NSString *)kCTForegroundColorAttributeName];
Run Code Online (Sandbox Code Playgroud)