【问题标题】:How can I do programmatically gradient border color UIButton with Swift [closed]如何使用 Swift 以编程方式渐变边框颜色 UIButton [关闭]
【发布时间】:2016-08-18 14:18:00
【问题描述】:

如何以编程方式设计像这种渐变边框颜色的 UIButton?

]

感谢您的帮助

【问题讨论】:

标签: ios iphone uibutton swift2 gradient


【解决方案1】:
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)

【讨论】:

  • 它可以工作,但是否有可能使角落变圆而不是尖?
  • @Ahmad 你可以使用cornerRadius属性
  • 添加圆角半径 shape.path = UIBezierPath(roundedRect: self.myButton.bounds,cornerRadius: self.myButton.cornerRadius).cgPath
  • 不要忘记添加self.myButton.clipsToBounds = true 以显示正确的圆角半径
  • 要在 Swift 4.2 + 中添加圆角半径,请使用以下代码:myButton.layer.cornerRadius = 25 shape.path = UIBezierPath(roundedRect: myButton.bounds, cornerRadius: myButton.layer.cornerRadius).cgPath cornerRadius 是图层的属性,而不是 UIButton 的属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
相关资源
最近更新 更多