How to draw NSAttributedString with .background attributes and insets?

71 views Asked by At

I need to draw in CALayer subclass NSAttributedString with background for every line of text and insets(horizontal and vertical). How to do that?

I am trying this code. But, I can't set insets text insets.

override func draw(in ctx: CGContext) {
        if let attributedString = nsAttributedString {

            ctx.translateBy(x: 0, y: (bounds.size.height * 1.5) - (stringSize.height / 2))
            ctx.scaleBy(x: 1.0, y: -1.0)

            let path = CGMutablePath()
            path.addRect(bounds)

            let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
            let frame = CTFramesetterCreateFrame(framesetter,
                                                 CFRangeMake(0, attributedString.length),
                                                 path, nil)

            ctx.textMatrix = .identity
            ctx.textPosition = .zero
          
            CTFrameDraw(frame, ctx)
        }
    }

Its should looks like this

0

There are 0 answers