圆形GAGradient图层上的锯齿状边缘

时间:2017-09-11 11:17:22

标签: ios swift cashapelayer cagradientlayer

我正在尝试绘制一个用渐变填充的圆形进度条。我的代码如下:

    override func draw(_ rect: CGRect) {
        let circlePath = UIBezierPath(arcCenter: CGPoint(x: rect.size.width / 2.0, y: rect.size.height / 2.0), radius: rect.size.height / 2.0, startAngle: 0.0, endAngle: CGFloat.pi * 2.0, clockwise: true)
        circleLayer.path = circlePath.cgPath
        circleLayer.fillColor = UIColor.clear.cgColor
        circleLayer.strokeColor = UIColor(hex: 0xCACACA).cgColor
        circleLayer.lineWidth = 2.0
        circleLayer.strokeEnd = 1.0
        layer.addSublayer(circleLayer)


        let circleCorrectPath = UIBezierPath(arcCenter: CGPoint(x: rect.size.width / 2.0, y: rect.size.height / 2.0), radius: rect.size.height / 2.0, startAngle: CGFloat.pi * 3/2, endAngle: CGFloat.pi * 3/2 + CGFloat.pi * 2, clockwise: true)
        progressCircleLayer.path = circleCorrectPath.cgPath
        progressCircleLayer.fillColor = UIColor.clear.cgColor
        progressCircleLayer.strokeColor = UIColor.black.cgColor
        progressCircleLayer.lineWidth = 2.0
        layer.addSublayer(progressCircleLayer)

        let gradient = CAGradientLayer()
        gradient.frame = rect
        gradient.mask = progressCircleLayer
        gradient.colors = [UIColor(red:0.52, green:0.83, blue:0.9, alpha:1).cgColor,
                              UIColor(red:0.25, green:0.67, blue:0.86, alpha:1).cgColor]
        gradient.locations = [0, 1]
        gradient.startPoint = CGPoint(x: 1, y: 0)
        gradient.endPoint = CGPoint.zero
        layer.addSublayer(gradient)

    }

但是这看起来渐变层看起来有锯齿状的边缘:

enter image description here

在图像中,底边和右边是锯齿状的。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您的问题不在于CAGradientLayer,而在于CAShapeLayer(代码中的progressCircleLayer)。

对于视网膜设备,CAShapeLayer的光栅化属性默认为1,导致图像模糊。

progressCircleLayer.shouldRasterize = true
progressCircleLayer.rasterizationScale = 2 * UIScreen.main.scale