我有一個簡單的示例應用程序,我創建了一個CATextLayer
並將其string
屬性設置爲NSAttributedString
。然後我將CATextLayer添加到視圖中。在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。
我始終* *忘記使用.CGColor在CoreGraphics級別工作時。非常感謝! –