我该如何以编程方式设计类似于这个渐变边框颜色的UIButton?
感谢您的帮助。
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)
self.myButton.clipsToBounds = true
以正确显示圆角半径。 - Ivan SmetaninmyButton.layer.cornerRadius = 25 shape.path = UIBezierPath(roundedRect: myButton.bounds, cornerRadius: myButton.layer.cornerRadius).cgPath
cornerRadius
是层的属性,而不是UIButton的属性。 - Pankaj Kulkarni