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.
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.
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:-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With