Ho una semplice app di esempio in cui creo un CATextLayer
e imposta la sua proprietà string
a NSAttributedString
. Quindi aggiungo CATextLayer a una vista.Visualizzazione di una stringa attribuita in un 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];
}
Questo funziona perfettamente nel simulatore tranne che il testo è nero anziché blu. Quando si esegue su un dispositivo, tutto viene visualizzato come fa sul simulatore ma genera i seguenti due errori nella console.
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Devo impostare un CGContext da qualche parte? Sto impostando i miei attributi in modo errato? Sono completamente sulla strada sbagliata. Nota, questo per un'app iOS 5.x e voglio usare un CATextLayer
per motivi di prestazioni. La vera applicazione avrà moltiCATextLayer
s.
I * sempre * dimentica di usare .CGColor quando si lavora a livello CoreGraphics. Grazie mille! –