CATextLayer does not draw NSAttributedString background color

I have a CATextLayer and you want to set the background color for part of the string. But setting the background color for the attribute string (NSBackgroundColorAttributeName) has no effect. Other attributes, such as foreground color, are applied correctly.

NSMutableAttributedString *str = [[[NSMutableAttributedString alloc] initWithString:@"Some Text"] autorelease]; NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSColor yellowColor], NSForegroundColorAttributeName, [NSColor redColor], NSBackgroundColorAttributeName, nil]; [str setAttributes:attributes range:NSMakeRange(0, 3)]; textLayer.string = str; 

The first three characters are drawn in yellow, but the background does not change. Any ideas?

+4
source share
1 answer

I think the CATextLayer class uses the CoreText API to render it. The CoreText API CoreText very low-level and only supports a subset of the NSAttributedString attributes. Unfortunately, NSBackgroundColorAttributeName not one of them. You must deal with it manually (see this SO entry) .

+3
source

All Articles