UIButton上的圆角渐变边框

4

你好,我一直在尝试在我的应用程序中实现一个带有圆角和渐变边框的UIButton。我已经使用以下代码在我的按钮上创建了渐变边框:

    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)

这段代码可以成功创建边框,但如图片所示,圆角效果不佳。我尝试过其他技巧,但有些甚至会让圆角完全消失。

my button with the above code

此外,我需要按钮是透明填充的,因此我不能简单地制作渐变填充。如果有人能为我解决这个问题,我将不胜感激。
1个回答

9
在使用UIButton的bounds和cornerRadius创建UIBezierPath之前,您需要设置圆角半径。
请尝试以下操作:
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)

输出:

输出:

enter image description here


如何为渐变边框添加阴影 - nickypatson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接