我想要的是一个自定义UIButton,它有一个渐变边框(只是边框是渐变)和圆角。我几乎到了我想去的地方,但是角落有问题。 这是我目前拥有的:
这是我的代码:
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)
}
所以问题是如何用渐变显示角落?
答案 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
使用insets
和cornerRadius
的值进行游戏,以达到理想的效果。