J'ai un exemple d'application simple où je crée un CATextLayer
et définissez sa propriété string
sur NSAttributedString
. J'ajoute ensuite ce CATextLayer à une vue.Affichage d'une chaîne affectée dans une 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];
}
Cela fonctionne très bien dans le simulateur, sauf que le texte est noir au lieu de bleu. Lors de l'exécution sur un périphérique, tout s'affiche comme sur le simulateur mais génère les deux erreurs suivantes dans la console.
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Dois-je définir un CGContext quelque part? Est-ce que je mets mes attributs mal? Suis-je complètement sur la mauvaise piste. Remarque, ceci pour une application iOS 5.x et je veux utiliser un CATextLayer
pour des raisons de performances. La vraie application va avoir beaucoupCATextLayer
s.
I * toujours * oublier d'utiliser .CGColor lorsque vous travaillez au niveau CoreGraphics. Merci beaucoup! –