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
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.
You must use CGColor
instead of UIColor
for kCTForegroundColorAttributeName
:
[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
forKey:(NSString *)kCTForegroundColorAttributeName];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With