Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CATextlayer set line spacing?

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.

like image 996
Cong Tran Avatar asked Jul 22 '13 04:07

Cong Tran


2 Answers

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 image 110
spinacher Avatar answered Nov 15 '22 13:11

spinacher


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)
    }
}
like image 24
torof Avatar answered Nov 15 '22 12:11

torof