Display attribute string in CATextLayer

I have a simple example application where I create a CATextLayer and set its string property to NSAttributedString . Then I add that CATextLayer to the 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 a simulator, except that the text is black, not blue. When working on the device, everything is displayed 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 install CGContext somewhere? Am I setting my attributes incorrectly? I am completely mistaken. Please note: this is for iOS 5.x application, and I want to use CATextLayer for performance reasons. A real application will have many CATextLayer s.

+8
ios objective-c
source share
2 answers

You should use CGColor instead of UIColor for kCTForegroundColorAttributeName :

 [attributes setObject:(__bridge id)[UIColor blueColor].CGColor forKey:(NSString *)kCTForegroundColorAttributeName]; 
+12
source share

I converted this to Swift 3 and put it inside SpriteKit:

 import QuartzCore import SpriteKit class GameScene: SKScene { var textLayer = CATextLayer() func helloWord() { let fontFace = CTFontCreateWithName((("HelfaSemiBold") as CFString), 24.0, nil) var attributes: [AnyHashable: Any]? = [:] attributes?[(kCTFontAttributeName as String)] = fontFace attributes?[(kCTForegroundColorAttributeName as String)] = UIColor.blue.cgColor let attrStr = NSAttributedString(string: "Hello Attributed Word!", attributes: attributes as! [String : Any]?) textLayer.backgroundColor = UIColor.white.cgColor textLayer.frame = CGRect(x: CGFloat(50), y: CGFloat(200), width: CGFloat(300), height: CGFloat(100)) textLayer.contentsScale = UIScreen.main.scale textLayer.string = attrStr self.view?.layer.addSublayer(textLayer) } override func didMove(to view: SKView) { helloWord() } } 
0
source share

All Articles