如何在Swift中创建一个渐变的圆形路径

3

我想要创建一个如下图所示的渐变圆形路径:

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
可能是[Swift:沿着bezier路径渐变(使用CALayers)]的重复问题(https://dev59.com/el4c5IYBdhLWcg3wa56M)。 - canister_exister
可能是 https://dev59.com/N18e5IYBdhLWcg3wLYHt 的重复问题。 - Mosbah
2个回答

0

我也遇到了这个问题,并通过将半径值更改为预期值以下来解决它

在circularPath中,您需要确保半径值不大于以下值

let radius = (min(width, height) - lineWidth) / 2

circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)

0

看起来渐变层的框架被设置为与路径框架相等,但不包括CAShapeLayer描边的粗细,这就是为什么它被切成一个正方形的原因。我无法从代码中看出您是否在子视图上设置了圆形路径,但如果将渐变框架设置为与子视图框架相同,则应该能解决截断问题以及进度视图在轨道上的错位。

希望有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接