iOS 利用动画和贝塞尔实现咻咻效果

2020-01-18 13:48:52于丽


- (CAShapeLayer *)creatCircleShapWithPostion:(CGPoint)position
                  pathRect:(CGRect)rect
                   radius:(CGFloat)radius
{
  CAShapeLayer *circleShap = [CAShapeLayer layer];

// 从贝塞尔曲线取到形状
  circleShap.path = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:radius].CGPath;

// 虽然得到了形状, 但是并没有得到具体的 frame(bounds) 也就是实际上并没有范围 只是可以展现动画的效果 那么锚点其实就是设置的位置点
  circleShap.position = position;
  if (self.buttonType == DDFlashButtonInner)
  {
# 在这里设置 frame 就是为了满足我们想要的锚点位置让动画效果动起来, 下面也一样, 可以不设置试试效果就明白了!
   // circleShap.bounds = CGRectMake(0, 0, radius *2, radius *2);
   circleShap.frame = CGRectMake(position.x-radius, position.y-radius, radius*2, radius*2);
    // 线宽
    circleShap.lineWidth = 1;
    // 填充的颜色 不设置默认就给黄色
    circleShap.fillColor = self.flashColor ? self.flashColor.CGColor:[UIColor yellowColor].CGColor;

  }else
  {
     circleShap.frame = self.bounds;
   // 线宽
    circleShap.lineWidth = 5;
    circleShap.fillColor = [UIColor clearColor].CGColor;
  // 边缘线的颜色 不设置就默认给个紫色
  circleShap.strokeColor = self.flashColor ? self.flashColor.CGColor:[UIColor purpleColor].CGColor;

  }

  // 不透明度 要设置成透明的 不然内部风格的时候会画出来图案点点
  circleShap.opacity = 0;
  return circleShap;
}

第 7 步 : 把点击的事件完成就 OK 了


- (void)didTap:(UITapGestureRecognizer *)tapGesture
{
// 获取点击点的位置
  CGPoint tapLocation = [tapGesture locationInView:self];
// 定义一个图层 下面分情况去给予不同形状  
 CAShapeLayer *circleShape = nil;
// 默认一个变化比例 1 倍
   CGFloat scale = 1.0f;
// 获取 View 的宽和高
   CGFloat width = self.bounds.size.width, height = self.bounds.size.height;
   if (self.buttonType == DDFlashButtonInner)
  {
# 这里就是在视图内部效果, 就是以点击的点为圆心 画一个小圆(这里是半径为1) 然后让它动画起来 (不断的变大并变透明) 所以放大倍数只要能到最大的变就行了 不一定非要这样写, 你开心就好!
    CGFloat biggerEdge = width > height ? width :height; 
    CGFloat radius = 1
    scale = biggerEdge / radius + 0.5;
# 调用方法获得图层 锚点位置就是点击的位置
circleShape = [self creatCircleShapWithPostion:CGPointMake(tapLocation.x , tapLocation.y ) pathRect:CGRectMake(0, 0, radius * 2, radius * 2) radius:radius];   
  }else
  {
# 这个是外部动画效果 设置能放大5.5倍
    scale = 5.5f;
# 锚点位置在 View 的中心 这个图层和 View 是一样的形状范围
   circleShape = [self creatCircleShapWithPostion:CGPointMake(width /2 , height / 2) pathRect:self.bounds radius:self.layer.cornerRadius];
   }
// view图层 上添加 有形状的自定义图层
  [self.layer addSublayer:circleShape];

# 给自定义图层添加动画  
  [circleShape addAnimation:[self createFlashAnimationWisthScale:scale duration:1.0f] forKey:nil];
}