Search code examples
swifttextbackgroundcornerradius

Colored text background with rounded corners


I'm currently working on an iOS application in Swift, and I need to achieve the text effect shown in the attached picture.

I have a label which displays some text wrote by the user, and I need to make the text background corners (not the label background) rounded.

Is there a way to do that? I'd search the web and Stackoverflow but with no luck.

Thank you.

What I need to achieve


Solution

  • Here is some code that could help you. The result I got is quite similar to what you want.

    class MyTextView: UITextView {
    
        let textViewPadding: CGFloat = 7.0
    
        override func draw(_ rect: CGRect) {
            self.layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, self.text.count)) { (rect, usedRect, textContainer, glyphRange, Bool) in
    
                let rect = CGRect(x: usedRect.origin.x, y: usedRect.origin.y + self.textViewPadding, width: usedRect.size.width, height: usedRect.size.height*1.2)
                let rectanglePath = UIBezierPath(roundedRect: rect, cornerRadius: 3)
                UIColor.red.setFill()
                rectanglePath.fill()
            }
        }
    }
    

    enter image description here