我有一个像 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/