Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CATextLayer font borderColor?

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?

enter image description here

like image 405
strave Avatar asked Feb 22 '23 23:02

strave


2 Answers

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.

like image 135
strave Avatar answered Mar 05 '23 18:03

strave


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...
}
like image 31
Rick Avatar answered Mar 05 '23 16:03

Rick