OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 Swift 中制作渐变圆形路径 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 21:46
标题: ios - 如何在 Swift 中制作渐变圆形路径

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

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

如果有人帮助我,我将不胜感激,谢谢。



Best Answer-推荐答案


看起来渐变层框架设置为等于路径框架,不包括 CAShapeLayer 的笔划厚度,这就是为什么它被截断为正方形。我无法从代码中看到 subview 上是否有圆形路径,但是如果将渐变框架设置为与应该对截断进行排序的 subview 框架相同,以及轨道上进度 View 的错位.

希望对您有所帮助。

关于ios - 如何在 Swift 中制作渐变圆形路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54223709/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4