Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an attributed string in a 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

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 CATextLayers.

like image 238
Michael Luton Avatar asked Apr 17 '13 06:04

Michael Luton


1 Answers

You must use CGColor instead of UIColor for kCTForegroundColorAttributeName:

[attributes setObject:(__bridge id)[UIColor blueColor].CGColor
               forKey:(NSString *)kCTForegroundColorAttributeName];
like image 159
Vitaly Berg Avatar answered Nov 08 '22 14:11

Vitaly Berg