如何在Swift中制作渐变圆形路径

时间:2019-01-16 19:06:17

标签: ios swift uibezierpath cashapelayer cagradientlayer

我要创建一个渐变圆形路径,如下图:

enter image description here

,我有以下代码:

    circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
    outerTrackShapeLayer = CAShapeLayer()
    outerTrackShapeLayer.path = circularPath.cgPath
    outerTrackShapeLayer.position = position
    outerTrackShapeLayer.strokeColor = outerTrackColor.cgColor
    outerTrackShapeLayer.fillColor = UIColor.clear.cgColor
    outerTrackShapeLayer.lineWidth = lineWidth
    outerTrackShapeLayer.strokeEnd = 1
    outerTrackShapeLayer.lineCap = CAShapeLayerLineCap.round
    outerTrackShapeLayer.transform = rotateTransformation
    addSublayer(outerTrackShapeLayer)

    innerTrackShapeLayer = CAShapeLayer()
    innerTrackShapeLayer.strokeColor = innerTrackColor.cgColor
    innerTrackShapeLayer.position = position
    innerTrackShapeLayer.strokeEnd = progress
    innerTrackShapeLayer.lineWidth = lineWidth
    innerTrackShapeLayer.lineCap = CAShapeLayerLineCap.round
    innerTrackShapeLayer.fillColor = UIColor.clear.cgColor
    innerTrackShapeLayer.path = circularPath.cgPath
    innerTrackShapeLayer.transform = rotateTransformation
    let gradient = CAGradientLayer()
    gradient.frame = circularPath.bounds
    gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
    gradient.position = innerTrackShapeLayer.position
    gradient.mask = innerTrackShapeLayer
    addSublayer(gradient)

但是它不能正常工作,您可以在下图中看到结果:

enter image description here

如果有人帮助我,我会很感激。

1 个答案:

答案 0 :(得分:0)

似乎渐变层框架设置为等于路径框架,其中不包括CAShapeLayer的笔触粗细,这就是为什么将其切成正方形。我无法从代码中看到子视图上是否具有圆形路径,但是如果将渐变框设置为与应该对切除以及轨道上进度视图的未对齐进行排序的子视图框相同

希望有帮助。