Search code examples
iosquartz-graphicscore-text

Text becomes invisible when stroke is added


I have next issue (sample code below):
I'm use CATextLayer and NSAttributedString to displaying stylized text. All work fine until I had added stroke to attributes. When I add stroke - text becomes invisible and in display I can see only stroke. Please, I can't understand what happens, why I can't use both text and stroke? Thanks.

UIFont* font = [UIFont fontWithName: size:];
UIColor* strokeColor = [UIColor colorWithRed: green: blue: alpha:1.f];
UIColor* foregroundColor = [UIColor colorWithRed: green: blue: alpha:1.f];
CTFontDescriptorRef fontDescriptor = CTFontDescriptorCreateWithNameAndSize(...);
CTFontRef ctFont = CTFontCreateWithFontDescriptor(...);

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            strokeWidth, kCTStrokeWidthAttributeName,
                            [strokeColor CGColor], kCTStrokeColorAttributeName,
                            ctFont, kCTFontAttributeName,
                            [foregroundColor CGColor], kCTForegroundColorAttributeName,
                            nil];

NSAttributedString* attributedText = 
[[NSAttributedString alloc] initWithString:text attributes:attributes];

CATextLayer* infoTextLayer = [[[CATextLayer alloc] init] autorelease];
infoTextLayer.string = attributedText;
...
infoTextLayer.frame = frame;
[self.layer addSublayer:infoTextLayer];

Solution

  • Your strokeWidth must be negative for text and stroke and positive for only stroke. From Apple Docs:

    kCTStrokeWidthAttributeName. This attribute, interpreted as a percentage of font point size, controls the text drawing mode: positive values effect drawing with stroke only; negative values are for stroke and fill.