用Swift如何编程实现渐变边框UIButton?

26

我该如何以编程方式设计类似于这个渐变边框颜色的UIButton?

渐变按钮

感谢您的帮助。


请查看此链接:https://dev59.com/yF0b5IYBdhLWcg3wA9LI - kb920
我需要渐变边框颜色,请点击链接:) - m.akyol
请点击以下链接:https://dev59.com/WWUp5IYBdhLWcg3wj4Lu https://dev59.com/d2LVa4cB1Zd3GeqPz9Bd - Sheereen S
1个回答

62
let gradient = CAGradientLayer()
gradient.frame =  CGRect(origin: CGPointZero, size: self.myButton.frame.size)
gradient.colors = [UIColor.blueColor().CGColor, UIColor.greenColor().CGColor]

let shape = CAShapeLayer()
shape.lineWidth = 2
shape.path = UIBezierPath(rect: self.myButton.bounds).CGPath
shape.strokeColor = UIColor.blackColor().CGColor
shape.fillColor = UIColor.clearColor().CGColor
gradient.mask = shape

self.myButton.layer.addSublayer(gradient)

Swift 3版本:

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

    let shape = CAShapeLayer()
    shape.lineWidth = 2
    shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    self.myButton.layer.addSublayer(gradient)

3
可以正常运作,但是是否可能将角落变为圆角而不是尖角呢? - Ahmad
1
@Ahmad,你可以使用cornerRadius属性。 - Hellojeffy
12
为按钮添加圆角: shape.path = UIBezierPath(roundedRect: self.myButton.bounds, cornerRadius: self.myButton.cornerRadius).cgPath。 - Sameh
2
不要忘记添加 self.myButton.clipsToBounds = true 以正确显示圆角半径。 - Ivan Smetanin
4
要在Swift 4.2+中添加圆角,请使用以下代码:myButton.layer.cornerRadius = 25 shape.path = UIBezierPath(roundedRect: myButton.bounds, cornerRadius: myButton.layer.cornerRadius).cgPath cornerRadius是层的属性,而不是UIButton的属性。 - Pankaj Kulkarni
显示剩余2条评论

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