【问题标题】:Center of CAGradientLayer returns wrong position on rotate animationCAGradientLayer 的中心在旋转动画上返回错误的位置
【发布时间】:2019-03-08 14:18:28
【问题描述】:

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

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

我怎样才能在 Instagram 故事圈中实现动画(就像圆圈在旋转)?

编辑我也尝试添加 "colors" 动画,但因为它像正方形一样工作,我无法获得所需的结果。

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")
    }

【问题讨论】:

    标签: ios swift cashapelayer caanimation cagradientlayer


    【解决方案1】:

    如果旋转,为什么不旋转gradient

       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
    

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

     self.background = UIColor.black.
    

    原因是视图的widthheight由于约束没有设置好。尝试设置视图的正确边界,因此当您添加圆形路径时,它位于视图的中心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2022-11-08
      相关资源
      最近更新 更多