首页 文章

UIButton具有渐变边框和圆角

提问于
浏览
1

我想要的是一个自定义UIButton,它有一个渐变边框(只是边框是渐变)和圆角 . 我几乎到了我想去的地方,但是角落有问题 . 这是我目前拥有的:
enter image description here

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myButton.frame.size)
    gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.cornerRadius = 15

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

    self.myButton.clipsToBounds = true
    self.myButton.layer.cornerRadius = 15
    self.myButton.layer.addSublayer(gradient)
}

所以问题是我如何用渐变显示角落?

1 回答

  • 3

    问题是掩码,尝试删除 shape.cornerRadius = 15 并更改此:

    shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
    

    对此:

    shape.path = UIBezierPath(roundedRect: self.myButton.bounds.insetBy(dx: 2.5, dy: 2.5), cornerRadius: 15.0).cgPath
    

    使用 insetscornerRadius 的值来播放以获得所需的结果 .

相关问题