CATextLayer borderColor font?

I want my text to be surrounded by a white frame. I am using CATextLayer for text. I know that for CATextLayer there is no borderColor / borderWidth property. Of course, I can use the properties of my superclass (CALayer), but then it draws a border around the frame of the layer, and not around the text itself. Does anyone know how I can achieve this using CATextLayer?

enter image description here

+4
source share
2 answers

Just in case, someone is interested in my solution:

In principle, text with a stroke (border) can be made without using CoreText directly. The string property CATextLayer accepts NSAttributedStrings. Therefore, it would be as simple as providing the NSAttributedString with the color of the stroke and the width of the stroke in its attributes.

Unfortunately, I needed to animate the font size. The string property is animated, but only if it is an NSString. So I decided to subclass CATextLayer. After much effort, I realized that the string and the properties of the CATextLayer content are mutually exclusive, which means the string or content is being displayed. I could not understand how to draw a string myself. The display and drawInContext: ctx methods are only called when the content is updated, but I did not know what I would need to call to update the line.

So, I decided to write my own CATextLayer class, subclassing CALayer. I created an animated property called fontSize. When this one is animated, the drawInContext: ctx method is called. In the drawInContext: ctx method, I create a new line with a CoreText and update its size accordingly using the fontSize property.

+5
source

For anyone interested in a solution without worrying about font size animations:

@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... } 
+3
source

Source: https://habr.com/ru/post/1388952/


All Articles