搜索
您的当前位置:首页正文

iOS 扇形图动画效果

来源:二三娱乐

动画效果如图所示:

loadAnimation.gif

这天儿是真特么热啊,现在的基本状态就是:晚上热的睡不着、早上困得醒不来、白天工作没精神……照这样下去,估计是要废。大家有啥好的“抗日”绝招,欢迎分享。
  废话不多说,由于项目中上传音频文件到服务器的过程中,需要展示这样的动画,于是花费了半上午时间实现了该效果。
  首先,使用贝塞尔曲线配合CAShapeLayer画了个圆;
  其次,将CAShapeLayer作为animationView的layer遮罩;
  最后,使用CABasicAnimation对CAShapeLayer的strokeEnd属性实现动画效果。(该属性取值范围为0.0~1.0).

对应的代码如下:

 override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let width = CGRectGetWidth(animationView.frame)
        let height = CGRectGetHeight(animationView.frame)
        
        let centerX = width / 2
        let centerY = height / 2

        let path = UIBezierPath.init(arcCenter: CGPointMake(centerX, centerY), radius: width / 4, startAngle:CGFloat(-M_PI / 2), endAngle:CGFloat(3 * M_PI / 2), clockwise: true)
    
        layer.fillColor = UIColor.clearColor().CGColor //必须为clearColor
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.lineWidth = width / 2 //线宽为animationView高度一半
        layer.path = path.CGPath
        
        animationView.layer.mask = layer
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let animation = CABasicAnimation.init(keyPath: "strokeEnd")
        animation.duration = 5.0
        animation.fromValue = 0.0
        animation.toValue = 1.0
        layer .addAnimation(animation, forKey: "key")
    }

中间也踩了很多坑,由于半径和线宽取值不同对应的动画效果也不同,要想实现这样的扇形动画效果,经过多次尝试,最终确认:
  (1)贝塞尔曲线的radius必须为animationView高度的四分之一;
  (2)CAShapeLayer的线宽必须为animationView高度的二分之一;
  对于这两个值为什么一个是四分之一,一个是二分之一,我也没太弄明白,如果有知道原因的同学,请指教,谢谢。

Top