I have a problem with CATextlayer. I set wrapped == YES for CATextlayer and it auto set multi line for this. But the line spacing is very small and look it verry bad. Is there any way to set line spacing for CATextlayer? Thanks.
I think CATextLayer
is only intended for lightweight uses. You can set its string
property to an NSAttributedString
to alter some attributes like font and size but many others are ignored, including line height and spacing.
For finer control over how text in a layer is rendered you can use a regular CALayer
and NSAttributedString
’s drawing methods; for example:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]];
[self.someAttributedString drawInRect:layer.bounds];
[NSGraphicsContext restoreGraphicsState];
}
Like @spinacher I noticed that CATextLayer
ignores paragraph styles like line spacing. I solved this by subclassing CALayer and draw the attributed string more directly. Much of the code is copied from this article
class CAAttributedTextLayer: CALayer {
public var attrString = NSAttributedString(string: "")
override func draw(in ctx: CGContext) {
// Flip the coordinate system
ctx.textMatrix = .identity
ctx.translateBy(x: 0, y: bounds.size.height)
ctx.scaleBy(x: 1.0, y: -1.0)
let path = CGMutablePath()
path.addRect(bounds)
let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)
CTFrameDraw(frame, ctx)
}
}
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