问题描述
我有一个简单的示例应用程序,我在其中创建了一个 CATextLayer
并将其 string
属性设置为 NSAttributedString
.然后我将该 CATextLayer 添加到视图中.
I have a simple example app where I create a CATextLayer
and set its string
property to an NSAttributedString
. I then add that CATextLayer to a view.
#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];
}
这在模拟器中效果很好,除了文本是黑色而不是蓝色.在设备上运行时,一切都会像在模拟器上一样显示,但会在控制台中生成以下两个错误.
This works great in the simulator except the text is black instead of blue. When running on a device everything displays like it does on the simulator but it generates the following two errors in the console.
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
我应该在某处设置 CGContext 吗?我的属性设置错了吗?我是不是完全走错了轨道.请注意,这是针对 iOS 5.x 应用程序的,出于性能原因,我想使用 CATextLayer
.真正的应用程序将有许多 CATextLayer
s.
Should I be setting a CGContext somewhere? Am I setting my attributes wrong? Am I completely on the wrong track. Note, this for an iOS 5.x app and I want to use a CATextLayer
for performance reasons. The real app is going to have many CATextLayer
s.
推荐答案
kCTForegroundColorAttributeName
必须使用 CGColor
而不是 UIColor
:>
You must use CGColor
instead of UIColor
for kCTForegroundColorAttributeName
:
[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
forKey:(NSString *)kCTForegroundColorAttributeName];
这篇关于在 CATextLayer 中显示属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!