带有渐变颜色的 ImageView 的圆角问题

Issue with rounded corners of ImageView with gradient colour

我使用以下代码创建了一个矩形,现在我需要圆化这个矩形的角。我也设置了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