ios - CAGradientLayer 的中心在旋转动画上返回错误的位置

标签 ios swift cashapelayer caanimation cagradientlayer

我有一个像 Instagram 个人资料图片中那样的圈子,里面有故事。我想要有一种像圆圈在旋转的感觉。为此,我使用了 CABasicAnimation。它正在旋转,但不在中心。

正如我搜索的那样,我需要为 shapeLayer 提供赏金,但是当我这样做时,它没有放置在需要的位置。

如何实现像 Instagram 故事圈一样的动画(就像圈在旋转)?

编辑我还尝试添加“颜色”动画,但因为它的工作原理就像它在正方形中一样,所以我无法获得所需的结果。

func addCircle() {
    let circularPath = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY), radius: self.bounds.width / 2, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.strokeEnd = 1.0

    gradient.frame = circularPath.bounds
    gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
    gradient.startPoint = CGPoint(x: 0, y: 1)
    gradient.endPoint = CGPoint(x: 1, y: 0)

    shapeLayer.path = circularPath.cgPath
    gradient.mask = shapeLayer
    self.layer.addSublayer(gradient)

}

let rotationAnimation: CAAnimation = {
    let animation = CABasicAnimation(keyPath: "transform.rotation")
    animation.fromValue = 0
    animation.toValue = 1
    animation.duration = 4
    animation.repeatCount = MAXFLOAT
    return animation
}()

@objc private func handleTap() {
        print("Attempting to animate stroke")
        shapeLayer.add(rotationAnimation, forKey: "urSoBasic2")
    }

最佳答案

如果旋转,为什么不旋转渐变

   let rotationAnimation: CAAnimation = {
    let animation = CABasicAnimation(keyPath: "transform.rotation")
    animation.fromValue = 0
    animation.toValue = Float.pi * 2
    animation.duration = 4
    animation.repeatCount = MAXFLOAT

    return animation
}()

@objc  func handleTap() {
    print("Attempting to animate stroke")
    gradient.add(rotationAnimation, forKey: "urSoBasic2")
}

关于偏离中心的问题。正确的渐变框架应该是这样的:

  gradient.frame = self.bounds

要验证中心,您可以为 View 添加背景:

 self.background = UIColor.black.

原因是由于限制, View 的宽度高度没有设置好。尝试设置 View 的正确边界,因此当您添加circularPath时,它位于 View 的中心。

关于ios - CAGradientLayer 的中心在旋转动画上返回错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55065094/

相关文章:

ios - 带有 UIBezierPath 的 CAShapeLayer

swift - 你能告诉 for 循环有条件地前进不止一步吗?

ios - 从 UITableView 导航到另一个 ViewController,然后返回到 TableViewController 会导致某些元素消失

android - Flutter布局不一致

ios - ‘SEL' 类型的集合元素不是 Objective-C 对象

ios - 类 CKPPTSubTest 在两个框架中都实现了。将使用两者之一。哪个是未定义的

ios - 如何为不同的屏幕尺寸设置不同的自动布局约束

ios - 缩放 CGPath 以适应 UIVIew

iOS:UIBezierPath 和 CAShapeLayer 填充规则

ios - 如何与Socket.io连接? swift 4