I would like my text to be surrounded by a white border. I'm using CATextLayer for the text. I know there is no property borderColor/borderWidth for the CATextLayer. Of course I can use the properties of its superclass (CALayer) but then it draws a border around the frame of the layer and not around the text itself. Does anybody know how I could achieve this using CATextLayer?
Just in case someone is interested in my solution:
Basically it is possible to make text with a stroke (border) without using CoreText directly. The string property of CATextLayer accepts NSAttributedStrings. Therefore it would be as easy as giving a NSAttributedString with a stroke color and a stroke width in its attributes.
Unfortunately I needed to animated the font size. The string property is animatable but only if it's an NSString. So I decided to subclass CATextLayer. After much trying I came to realize that the string and the contents properties of the CATextLayer are mutually exclusive, which means, either the string or the content is displayed. I couldn't figure out how to do the drawing of the string myself. The display and drawInContext:ctx methods are called only when the content is being updated but I didn't know what I would have to call for updating the string.
So I decided to write my own CATextLayer class, subclassing CALayer. I created an animatable property called fontSize. When this one is animated, the drawInContext:ctx method is called. In the drawInContext:ctx method I create a a new string with CoreText and update its size accordingly using the fontSize property.
For anyone interested in the solution without needing to worry about animating the font size:
@import QuartzCore;
@import CoreText;
- (void)addTextLayer
{
NSDictionary* attributes = @{ NSFontAttributeName : [UIFont boldSystemFontOfSize:40.0],
(NSString*)kCTForegroundColorAttributeName: (id)[UIColor blackColor].CGColor,
(NSString*)kCTStrokeWidthAttributeName: @(-2.0),
(NSString*)kCTStrokeColorAttributeName: (id)[UIColor whiteColor].CGColor };
CATextLayer* textLayer = [CATextLayer layer];
textLayer.string = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];
// Do the rest...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With