我正在尝试在视图控制器中制作动画,其中圆圈随动画旋转 . 圆圈应该旋转,直到一个过程像下面的gif一样完成 . 我已经实现了圆形动画,但无法达到我想达到的目的 .
import UIKit
class ViewController: UIViewController {
var circle : Circle?;
override func viewDidLoad() {
super.viewDidLoad();
view.backgroundColor = UIColor.white;
setupViews();
}
func setupViews(){
circle = Circle(frame: self.view.frame);
view.addSubview(circle!);
circle?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true;
circle?.topAnchor.constraint(equalTo: view.topAnchor).isActive = true;
circle?.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true;
circle?.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true;
}
}
class Circle : UIView{
override init(frame: CGRect) {
super.init(frame: frame);
self.backgroundColor = .blue;
self.translatesAutoresizingMaskIntoConstraints = false;
setupCircle();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let gradientLayer = CAGradientLayer();
func setupCircle(){
layer.addSublayer(shapeLayer);
let circlePath = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2 - 50, y: self.frame.height / 2 - 50), radius: 50, startAngle: CGFloat(Double.pi * (0 / 4)), endAngle: CGFloat(Double.pi * 2), clockwise: true);
shapeLayer.path = circlePath.cgPath;
let group = CAAnimationGroup()
group.animations = [animateStrokeEnd, animateOpacity]
group.duration = 0.8
group.repeatCount = HUGE // repeat forver
shapeLayer.add(group, forKey: nil)
}
let shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer();
layer.strokeColor = UIColor.white.cgColor;
layer.lineWidth = 5;
layer.fillColor = UIColor.clear.cgColor;
layer.strokeStart = 0
layer.strokeEnd = 1;
return layer;
}();
let animateOpacity : CABasicAnimation = {
let animation = CABasicAnimation(keyPath: "opacity");
animation.fromValue = 0;
animation.toValue = 0.8;
animation.byValue = 0.01;
animation.repeatCount = Float.infinity;
return animation
}();
let animateStrokeEnd: CABasicAnimation = {
let animation = CABasicAnimation(keyPath: "strokeEnd");
animation.fromValue = 0;
animation.repeatCount = Float.infinity;
animation.toValue = 1;
return animation;
}();
}
我正在使用strokeEnd动画来实现动画 . 并且不透明度可以为颜色设置动画 . 但是当圆圈达到360度时,它会在开始新圆圈之前产生延迟 .
有谁知道如何删除此效果并获得流畅的动画?
The above code produces this animation
But i want to achieve this animation
笔画颜色也与原始动画不同 . 我们可以使用CABasicAnimation实现这个动画吗?
1 回答
而不是尝试为实际绘图设置动画,只需绘制一次视图,然后为其设置动画 .
这是一个自定义
PadlockView
和一个自定义CircleView
,它模仿你显示的动画 . 要使用它,请将以下代码添加到项目中 . 将UIView
添加到故事板,将其类更改为PadlockView
,并为其创建@IBOutlet
(也许称为padlock
) . 如果希望视图设置动画,请设置padlock.circle.isAnimating = true
. 要停止动画,请设置padlock.circle.isAnimating = false
.CircleView.swift
PadlockView.swift
Note: 连续动画代码由this answer提供 .
这是我在
ViewController
中使用以下代码设置的演示: