我有一个像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")
}
如果旋转,为什么不旋转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.
原因是由于约束,视图的width
和height
设置得不好。尝试设置视图的正确边界,因此当您添加circularPath时,它在视图中居中。