类似微信朋友圈加载视频的扇形动画

用到的类及其简单的解释:

1、UIBezierPath:使用此类可以定义简单的形状,如椭圆或者矩形,或者有多个直线和曲线段组成的形状

2、CAShapeLayer:继承自CALayer,因此,可使用CALayer的所有属性。但是,CAShapeLayer需要和贝塞尔曲线配合使用才有意义。

3、CABasicAnimation:使用方式就是基本的关键帧动画。所谓关键帧动画,就是将Layer的属性作为KeyPath来注册,指定动画的起始帧和结束帧,然后自动计算和实现中间的过渡动画的一种动画方式。

4、CATransaction:CATransaction的作用是保证多个“Animatable”的变化同时进行。也就是说CALayer的属性修改需要依赖CATransaction。

扇形代码:


- (void)createSectorView{

  UIView *bgView = [[UIView alloc]initWithFrame:self.bounds];
  bgView.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255   alpha:0.4];
  [self addSubview:bgView];
  CGFloat width = self.frame.size.width;
  CGFloat height = self.frame.size.height;
  CGFloat centerX = width / 2;
  CGFloat centerY = height / 2;

  UIBezierPath *bezierPath = [UIBezierPath    bezierPathWithArcCenter:CGPointMake(centerX, centerY) radius:width / 4 startAngle:(CGFloat)(-M_PI / 2) endAngle:(CGFloat)(3 * M_PI / 2) clockwise:YES];

  _shapeLayer = [CAShapeLayer layer];
  [bgView.layer addSublayer:_shapeLayer];
  _shapeLayer.fillColor = [UIColor clearColor].CGColor;
  _shapeLayer.strokeColor = [UIColor colorWithRed:255 green:255 blue:255   alpha:0.6].CGColor;
  _shapeLayer.lineWidth = width / 2.0;
  _shapeLayer.path = bezierPath.CGPath;
  bgView.layer.mask = _shapeLayer;

}

如果你根据下载的进度来控制动画,方法如下:


- (void)startAnimationWithProgress:(CGFloat)progress {

  [CATransaction begin];
  [CATransaction setAnimationDuration:0.1];
  [CATransaction setCompletionBlock:^{
  }];
  [self.shapeLayer setStrokeEnd:progress];
  [CATransaction commit];

}

如果想直接是一个扇形的动画:


- (void)startAnimation{

  CABasicAnimation *animation = [CABasicAnimation animation];
  animation.keyPath = @"strokeEnd";
  animation.duration = 2.0;
  animation.fromValue = @0.0;
  animation.toValue = @1.0;
  animation.timingFunction = [CAMediaTimingFunction    functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  animation.removedOnCompletion = NO;
  //animation.fillMode = kCAFillModeRemoved;
  //[_shapeLayer setStrokeEnd:toEnd];
  [animation setDelegate:self];
  [_shapeLayer addAnimation:animation forKey:@"strokeEndAnimation"];

}

效果图如下:

效果.gif

你可能感兴趣的:(类似微信朋友圈加载视频的扇形动画)