Lucas Azzopardi
Lucas Azzopardi

Reputation: 1181

Rounded Gradient Border on UIButton

Hello I have been trying to implement a UIButton in my application that has rounded corners and a border that is a gradient. I have used the following code to create a gradient border on my button:

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
    gradient.colors = [colourOne.cgColor, colourTwo.cgColor]

    let shape = CAShapeLayer()
    shape.lineWidth = 6
    shape.path = UIBezierPath(roundedRect: self.myBtn.bounds, cornerRadius: 22).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    self.myBtn.layer.addSublayer(gradient)

This code works well to create the border, but as you can see from the picture, the corners are not rounded properly. Other techniques I have tried have made the rounded corners invisible altogether.

my button with the above code

Also, I need the button to be a transparent fill, so I cannot simply make a gradient fill.

If anyone can shed some light on this for me it would be greatly appreciated.

Upvotes: 4

Views: 3858

Answers (1)

Rajamohan S
Rajamohan S

Reputation: 7269

You need to set corner radius before creating UIBezierPath with UIButton bounds and cornerRadius.

Try below:

self.myBtn.layer.cornerRadius = self.myBtn.frame.height/2
self.myBtn.clipsToBounds = true

let gradient = CAGradientLayer()
gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
gradient.colors =  [UIColor.blue.cgColor, UIColor.green.cgColor]

let shape = CAShapeLayer()
shape.lineWidth = 6

shape.path = UIBezierPath(roundedRect: self.myBtn.bounds, cornerRadius: self.myBtn.layer.cornerRadius).cgPath

shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape

self.myBtn.layer.addSublayer(gradient)

Output:-

enter image description here

Upvotes: 11

Related Questions