UIButton具有渐变边框和圆角

时间:2018-02-16 15:26:16

标签: ios swift uibutton

我想要的是一个自定义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 个答案:

答案 0 :(得分: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的值进行游戏,以达到理想的效果。