Search code examples
swifttextviewrounded-corners

How to set layer cornerRadius for only bottom-left, bottom-right, and top-left corner?


How to set corner radius only only bottom-left, bottom-right, and top-left corners of a textview?

let rectShape = CAShapeLayer()
rectShape.backgroundColor = UIColor.redColor().CGColor
rectShape.bounds = messages.frame
rectShape.position = messages.center
rectShape.path = UIBezierPath(roundedRect: messages.bounds, byRoundingCorners: .BottomLeft | .TopRight, cornerRadii: CGSize(width: 20, height: 20)).CGPath

messages.layer.addSublayer(rectShape)

this code creates two rects. I dont know why.


Solution

  • You just need to mask the layer as shown below:

    For Swift 3:

    let rectShape = CAShapeLayer()
    rectShape.bounds = self.myView.frame
    rectShape.position = self.myView.center
    rectShape.path = UIBezierPath(roundedRect: self.myView.bounds, byRoundingCorners: [.bottomLeft , .bottomRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    
    self.myView.layer.backgroundColor = UIColor.green.cgColor
    //Here I'm masking the textView's layer with rectShape layer
    self.myView.layer.mask = rectShape
    

    Lower Version:

    let rectShape = CAShapeLayer()
    rectShape.bounds = self.myView.frame
    rectShape.position = self.myView.center
    rectShape.path = UIBezierPath(roundedRect: self.myView.bounds, byRoundingCorners: .BottomLeft | .BottomRight | .TopLeft, cornerRadii: CGSize(width: 20, height: 20)).CGPath
    
    self.myView.layer.backgroundColor = UIColor.greenColor().CGColor
    //Here I'm masking the textView's layer with rectShape layer
    self.myView.layer.mask = rectShape