我用下面的代码创建了一个矩形,现在我需要圆角这个矩形的角。我还设置了layer.cornerRadius,有人能帮我吗?
我的代码如下,
private func setGradientBorder(_ ivUser:UIImageView) {
ivUser.layer.masksToBounds = true
ivUser.layer.cornerRadius = ivUser.frame.width / 2
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: ivUser.frame.size)
gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
let maskPath = UIBezierPath(roundedRect: ivUser.bounds,
byRoundingCorners: [.allCorners],
cornerRadii: CGSize(width: ivUser.frame.width/2, height: ivUser.frame.height/2)).cgPath
let shape = CAShapeLayer()
shape.lineWidth = 2
shape.path = maskPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
ivUser.layer.addSublayer(gradient)
}
输出:渐变显示不正确舍入
最佳答案
这就是UIBezierPath的工作原理。一半的线宽将在实际路径的一侧,另一半将在另一侧。这就是为什么它看起来有点断章取义。
您需要将路径直接插入一半的行宽,如下所示:
let lineWidth: CGFloat = 2
let maskPath = UIBezierPath(roundedRect: ivUser.bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2),
byRoundingCorners: [.allCorners],
cornerRadii: CGSize(width: ivUser.frame.width/2, height: ivUser.frame.height/2)).cgPath
关于ios - 带有渐变颜色的ImageView的圆角问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50386428/