如何以编程方式使用Swift进行渐变边框颜色UIButton

m.a*_*yol 15 iphone gradient uibutton ios swift2

如何以编程方式设计UIButton,如此渐变边框颜色?

渐变按钮]

感谢帮助

gvu*_*sic 38

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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

  • 添加角半径shape.path = UIBezierPath(roundedRect:self.myButton.bounds,cornerRadius:self.myButton.cornerRadius).cgPath (4认同)
  • 它可以工作,但是有可能使拐角变圆而不是变得尖尖吗? (2认同)
  • 并且不要忘记添加 `self.myButton.clipsToBounds = true` 以显示正确的角半径 (2认同)
  • 要在 Swift 4.2 + 中添加圆角半径,请使用以下代码:`myButton.layer.cornerRadius = 25 shape.path = UIBezierPath(roundedRect: myButton.bounds,cornerRadius: myButton.layer.cornerRadius).cgPath`图层的属性而不是 UIButton 的属性。 (2认同)