您好,我一直在尝试在我的应用程序中实现一个 UIButton,它具有圆角和渐变边框。我使用以下代码在按钮上创建渐变边框:
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
gradient.colors = [colourOne.cgColor, colourTwo.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 6
shape.path = UIBezierPath(roundedRect: self.myBtn.bounds, cornerRadius: 22).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
self.myBtn.layer.addSublayer(gradient)
此代码可以很好地创建边框,但正如您从图片中看到的那样,边角没有正确倒圆。我尝试过的其他技术使圆角完全看不见。
另外,我需要按钮是透明填充,所以我不能简单地进行渐变填充。
如果有人能为我阐明这一点,我将不胜感激。
创建前需要设置圆角半径UIBezierPath
with UIButton
bounds
and cornerRadius
.
尝试以下:
self.myBtn.layer.cornerRadius = self.myBtn.frame.height/2
self.myBtn.clipsToBounds = true
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
let shape = CAShapeLayer()
shape.lineWidth = 6
shape.path = UIBezierPath(roundedRect: self.myBtn.bounds, cornerRadius: self.myBtn.layer.cornerRadius).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
self.myBtn.layer.addSublayer(gradient)
Output:-
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)