Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 473
Lucas Azzopardi Avatar asked Oct 19 '25 10:10

Lucas Azzopardi


1 Answers

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

like image 199
Rajamohan S Avatar answered Oct 21 '25 00:10

Rajamohan S