CAShapeLayer与UIBezierPath实现注水动画与正余弦水波纹动画,雷达扩散效果,添加购物车动画

初步学习了CoreAnimation框架,总结了几个动画效果,主要是通过CAShapeLayer与贝塞尔曲线实现。
推荐一个大神的博客:Kitten 的时间胶囊,爱好动画的可以看看。感觉数学好渣渣,是时候恶补一下了
先看下效果

gif.gif
扇形下载进度

要实现扇形的下载进度,有两种方法, 这里先使用第一种:
1.使用设置UIBezierPath的角度
2.使用 CAShapeLayer的stokeEnd属性

  //设置中心点
    CGPoint point = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    
    //起点位置
    CGFloat startAngle = - M_PI /2;
    
    //结束位置
    CGFloat endAngle = self.progress *M_PI *2 + startAngle;
    
    
    UIBezierPath *path =[UIBezierPath bezierPathWithArcCenter:point radius:self.bounds.size.width/2 startAngle:startAngle endAngle:endAngle clockwise:1];
    
     //画一根到 圆心的线
    [path addLineToPoint:point];
    
    
    //通过layer绘制
    CAShapeLayer *layer =[CAShapeLayer layer];
    
    
    layer.path = path.CGPath;
    
    layer.fillColor =[UIColor colorWithRed:0.47 green:0.83 blue:0.98 alpha:1].CGColor;
    
    [self.layer addSublayer:layer];
圆形进度
首先 我们需要一个背景层 一个前景层,一个路径供给两个layer使用。这里我们使用改变stokeEnd 来改变圆弧的进度,代码里增加了一点渐变
   self.backLayer =[CAShapeLayer layer];
    self.backLayer.fillColor  =[UIColor clearColor].CGColor;
    self.backLayer.frame = self.bounds;
    self.backLayer.lineWidth = 4;
    self.backLayer.strokeColor =[UIColor lightGrayColor].CGColor;
    [self.layer addSublayer:self.backLayer];
    
    self.foreLayer =[CAShapeLayer layer];
    self.foreLayer.fillColor  =[UIColor clearColor].CGColor;
    self.foreLayer.frame = self.bounds;
    self.foreLayer.strokeColor =[UIColor redColor].CGColor;
    self.foreLayer.lineWidth = 4;
    [self.layer addSublayer:self.foreLayer];
    
    
    UIBezierPath *path=  [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) radius:self.bounds.size.width/2-2 startAngle:-M_PI_2 endAngle:M_PI *1.5 clockwise:YES];
    self.backPath = path;
    
    self.backLayer.path = self.backPath.CGPath;
    self.foreLayer.path = self.backPath.CGPath;
    self.foreLayer.strokeEnd = 0;
    
    
    self.gradientLayerLeft =[CAGradientLayer layer];
    self.gradientLayerLeft.frame = self.bounds;
    
    self.gradientLayerLeft.colors =@[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor yellowColor].CGColor,(__bridge id)[UIColor blueColor].CGColor];
    self.gradientLayerLeft.locations = @[@0,@0.5,@1];
    self.gradientLayerLeft.startPoint = CGPointMake(0, 0);
    self.gradientLayerLeft.endPoint = CGPointMake(0, 1);
    [self.layer addSublayer:self.gradientLayerLeft];
  
    
    //设置mask
    [self.gradientLayerLeft setMask:self.foreLayer];
-(void)setProgressValue:(CGFloat)progressValue
{
    _progressValue = progressValue;
    self.foreLayer.strokeEnd = progressValue;
    self.label.text = [NSString stringWithFormat:@"%.f%%",progressValue *100];
}
一个加载动画

引自:旋转加载动画
可以重点学习下做动画的思路,

//核心代码 在动画开始的时候做一些平移旋转
- (void)animationDidStart:(CAAnimation *)anim{
    [UIView animateWithDuration:0.3 delay:0.1 options:UIViewAnimationOptionCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState animations:^{
        
        self.ball_1.transform = CGAffineTransformMakeTranslation(-BALL_RADIUS, 0);
        self.ball_1.transform = CGAffineTransformScale(self.ball_1.transform, 0.7, 0.7);
        
        self.ball_3.transform = CGAffineTransformMakeTranslation(BALL_RADIUS, 0);
        self.ball_3.transform = CGAffineTransformScale(self.ball_3.transform, 0.7, 0.7);
        
        
        self.ball_2.transform = CGAffineTransformScale(self.ball_2.transform, 0.7, 0.7);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 delay:0.1 options:UIViewAnimationOptionCurveEaseIn  | UIViewAnimationOptionBeginFromCurrentState animations:^{
            self.ball_1.transform = CGAffineTransformIdentity;
            self.ball_3.transform = CGAffineTransformIdentity;
            self.ball_2.transform = CGAffineTransformIdentity;
        } completion:NULL];
        
    }];
}

使用正余弦做的注水动画

在使用正余弦做注水动画时,先了解下正余弦

/**
 正弦曲线公式可表示为y=Asin(ωx+φ)+k:
 A,振幅,最高和最低的距离
 W,角速度,用于控制周期大小,单位x中的起伏个数
 K,偏距,曲线整体上下偏移量
 φ,初相,左右移动的值
 
 这个效果主要的思路是添加两条曲线 一条正玄曲线、一条余弦曲线 然后在曲线下添加深浅不同的背景颜色,从而达到波浪显示的效果
 */

我们要做的 就是使用两条正余弦,但是这两条正余弦, 波峰需要对应波谷,有两种方法:

  1. 使用for循环分别拼接正余弦的路径
-(void)updateWave
{
    //波浪宽度
    CGFloat waterWaveWidth = self.bounds.size.width;
    //初始化运动路径
    CGMutablePathRef path = CGPathCreateMutable();
    
    CGMutablePathRef maskPath = CGPathCreateMutable();
    //设置起始位置
    CGPathMoveToPoint(path, nil, 0, _waveY);
    
    //设置起始位置
    CGPathMoveToPoint(maskPath, nil, 0, _waveY);
    //初始化波浪其实Y为偏距
    CGFloat y = _waveY;
  
    //正弦曲线公式为: y=Asin(ωx+φ)+k;
    for (float x = 0.0f; x <= waterWaveWidth ; x++) {
        y = _waveAmplitude * sin(_wavePalstance * x + _waveX) + _waveY;
       
        CGPathAddLineToPoint(path, nil, x, y);

    }
    for (float x = 0.0f; x <= waterWaveWidth ; x++) {
        y = _waveAmplitude * cos(_wavePalstance * x + _waveX) + _waveY;
       
        CGPathAddLineToPoint(maskPath, nil, x, y);
    }
    [self updateLayer:_waveLayer1 path:path];
    [self updateLayer:_waveLayer2 path:maskPath];

}
-(void)updateLayer:(CAShapeLayer *)layer path:(CGMutablePathRef )path
{
    //填充底部颜色
    CGFloat waterWaveWidth = self.bounds.size.width;
    CGPathAddLineToPoint(path, nil, waterWaveWidth, self.bounds.size.height);
    CGPathAddLineToPoint(path, nil, 0, self.bounds.size.height);
    CGPathCloseSubpath(path);
    layer.path = path;
     CGPathRelease(path);
}


2.使用单个for循环只是 设置 另一条曲线的y值相反即可实现两条正余弦的效果 ,最后一个动画中会有说明

 for (int x = 0; x<WIDTH; x++) {
        y = waveHeight*sinf(0.01*waveCurvature*x+offSetValue*0.045);
        CGPathAddLineToPoint(path, nil, x, y);
        //遮罩层的路径与之相反
        masky = -y;
        CGPathAddLineToPoint(maskPath, nil, x, masky);
    }

但是我们有个需求就是改变 波浪的高度, 实现注水的百分比,就需要设置波浪的偏距

-(void)updateWaveY
{
    CGFloat targetY = self.bounds.size.height - _progress * self.bounds.size.height;
    if (_waveY < targetY) {
        _waveY += 2;
    }
    if (_waveY > targetY ) {
        _waveY -= 2;
    }
}
正余弦动画2

如果有个需求 ,比如一个小船 随着波浪的波动而起伏
那我们就需要计算 波浪的位置,然后设置小船的frame

//这里使用创建正余弦的第二种方法
    for (int x = 0; x<WIDTH; x++) {
        y = waveHeight*sinf(0.01*waveCurvature*x+offSetValue*0.045);
        CGPathAddLineToPoint(path, nil, x, y);
        //遮罩层的路径与之相反
        masky = -y;
        CGPathAddLineToPoint(maskPath, nil, x, masky);
    }
计算出实浪波动时,最中间的位置,设置小船的frame
  CGFloat CentY = waveHeight*sinf(0.01*waveCurvature*WIDTH/2+offSetValue*0.045);
    CGRect boardViewFrame = [boardView frame];
    boardViewFrame.origin.y = 100-waveHeight+CentY;
    boardView.frame = boardViewFrame;

雷达动画

gif.gif

给UIView添加一个分类

#import <UIKit/UIKit.h>

@interface UIView (RadarAnimation)

@property(nonatomic,strong)UIColor *radarColor; //扩散颜色
@property(nonatomic,assign)UIColor *radarBorderColor; //扩散边界颜色
-(void)addRadarAnimation;
@end

调用方法:

 button.radarColor = LBColor(237, 174, 130, 1);
 button.radarBorderColor = LBColor(237, 174, 130, 0.5);
  [button addRadarAnimation];

动画:添加动画的方法,创建三个layer,只不过,开始动画的时间要错开形成这个效果::

-(void)Animation{
    NSInteger pulsingCount = 3;
    double animationDuration = 2;

    CALayer * animationLayer = [[CALayer alloc]init];

    for (int i = 0; i < pulsingCount; i++) {
        CALayer * pulsingLayer = [[CALayer alloc]init];
        pulsingLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        pulsingLayer.backgroundColor = self.radarColor.CGColor;
        pulsingLayer.borderColor = self.radarBorderColor.CGColor;


        pulsingLayer.borderWidth = 1.0;
        pulsingLayer.cornerRadius = self.frame.size.height/2;

        CAMediaTimingFunction * defaultCurve = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

        CAAnimationGroup * animationGroup = [[CAAnimationGroup alloc]init];
        animationGroup.fillMode = kCAFillModeBoth;
        animationGroup.beginTime = CACurrentMediaTime() + (double)i * animationDuration/(double)pulsingCount;
        animationGroup.duration = animationDuration;
        animationGroup.repeatCount = HUGE_VAL;
        animationGroup.timingFunction = defaultCurve;

        CABasicAnimation * scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        scaleAnimation.autoreverses = NO;
        scaleAnimation.fromValue = [NSNumber numberWithDouble:1];
        scaleAnimation.toValue = [NSNumber numberWithDouble:1.5];

        CAKeyframeAnimation * opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
        opacityAnimation.values = @[[NSNumber numberWithDouble:1.0],[NSNumber numberWithDouble:0.5],[NSNumber numberWithDouble:0.3],[NSNumber numberWithDouble:0.0]];
        opacityAnimation.keyTimes = @[[NSNumber numberWithDouble:0.0],[NSNumber numberWithDouble:0.25],[NSNumber numberWithDouble:0.5],[NSNumber numberWithDouble:1.0]];
        animationGroup.animations = @[scaleAnimation,opacityAnimation];

        [pulsingLayer addAnimation:animationGroup forKey:@"pulsing"];
        [animationLayer addSublayer:pulsingLayer];
    }
        animationLayer.zPosition = -1;//重新加载时,使动画至底层
    [self.layer addSublayer:animationLayer];

}

爱奇艺旋转动画,说白了还是监听stokeStart stokeEnd做动画效果。

爱奇艺动画.gif

代码:

-(void)setUp{
    
    CGPoint point =  CGPointMake(self.width/2, self.height/2);
    UIBezierPath *path =[UIBezierPath bezierPathWithArcCenter:point radius:(self.width - 1)/2 startAngle:-0.5 *M_PI endAngle:1.5 *M_PI clockwise:YES];

    self.shapeLayer =[[CAShapeLayer alloc]init];
    self.shapeLayer.frame = self. bounds;
    
    self.shapeLayer.strokeColor = [UIColor hexStringToColor:@"#94BF3F"].CGColor;
    self.shapeLayer.fillColor =[UIColor clearColor].CGColor;
    self.shapeLayer.lineWidth = 1;
    self.shapeLayer.lineCap = kCALineCapRound;
    
 
    self.shapeLayer.path = path.CGPath;
    
    [self.layer addSublayer:self.shapeLayer];
    
    
  
    self.imageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 9, 9)];
    self.imageView.center = point;
    self.imageView.image =[UIImage imageNamed:@"三角形"];
    
    [self addSubview:self.imageView];
    [self animationOne];

}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if ([[anim valueForKey:@"animationName"] isEqualToString:@"AnimationEnd"]) {
        
        [self animationTwo];
        [self rotationAnimation];
    }
    if ([[anim valueForKey:@"animationName"] isEqualToString:@"AnimationStart"]) {
        
   
        [self.shapeLayer removeAllAnimations];
        [self animationOne];
    }
    
}
-(void)animationOne{
    
    self.shapeLayer.strokeStart=0;
    //设置strokeEnd的最终值,动画的fromValue为0,strokeEnd的最终值为0.98
    self.shapeLayer.strokeEnd=0.98;
    CABasicAnimation *basicAnimationOne=[CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    basicAnimationOne.fromValue=@(0);
    
    basicAnimationOne.duration= KAnimationDuration;
    
    basicAnimationOne.delegate=self;
    [basicAnimationOne setValue:@"AnimationEnd" forKey:@"animationName"];
    
    [self.shapeLayer addAnimation:basicAnimationOne forKey:@"animationName"];
}
-(void)animationTwo{
    
    self.shapeLayer.strokeStart = 0.98;
    CABasicAnimation *basicAnimationTwo=[CABasicAnimation animationWithKeyPath:@"strokeStart"];
    basicAnimationTwo.fromValue=@(0);
    
    basicAnimationTwo.duration= KAnimationDuration;
    
    basicAnimationTwo.delegate=self;
    [basicAnimationTwo setValue:@"AnimationStart" forKey:@"animationName"];
    

    [self.shapeLayer addAnimation:basicAnimationTwo forKey:@"animationName"];
    
}
-(void)rotationAnimation{
    CABasicAnimation *rotationAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    rotationAnimation.toValue=@(M_PI*2);
    rotationAnimation.duration= KAnimationDuration;
    
    rotationAnimation.delegate=self;
    [rotationAnimation setValue:@"AnimationRotation" forKey:@"animationName"];
    [self.imageView.layer addAnimation:rotationAnimation forKey:@"AnimationRotation"];
    

}

初学动画,参考很多文章,做个小小总结。
demo地址 demo集合

另外一个加入购物车的小动画:


12.gif
-(void)startAnimation
{
    //起点
    
    //控点
    CGPoint controlPoint = CGPointMake(_endPoint.x, _startPoint.y);
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:_startPoint];
    [path addQuadCurveToPoint:_endPoint controlPoint:controlPoint];
    
    CAShapeLayer *layer =[CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.strokeColor = [UIColor redColor].CGColor;
    layer.lineWidth = 3.0f;
    layer.shouldRasterize = YES;//抗锯齿
    [_viewController.view.layer addSublayer:layer];
    
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    //动画时间
    animation.duration = 1;
    animation.path = path.CGPath
    ;
    //当动画完成,停留到结束位置
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [_shopView.layer addAnimation:animation forKey:nil];
    path = nil;

}

贝塞尔曲线(加入购物车动画)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,952评论 4 60
  • 孤傲如我,与众不同,喜欢独来独往。 我,喜欢穿美丽的衣裳装扮自己的外貌, 也喜欢读美好的文字充实自己的内涵。 我,...
    风想留步阅读 1,128评论 1 9
  • 《安娜卡列尼娜》以安娜和列文两个人物为线索,一边是安娜走向悲剧的道路,一边是列文走向光明的道路,小说情节说不上很精...
    吃花大妖怪阅读 784评论 0 0
  • 这世界最有意思的地方,在于不可预料。 分享一则有意思的故事: 神经病院有一位老太太,每天都穿着黑色的衣服,拿着黑色...
    大东教练阅读 336评论 0 1
  • 不想间断运动,于是拖着昨天拉伤的腿去操场走了快一个小时。一步一步,慢慢走,伴着音乐。安静的夜晚总是让人多想。 最近...
    当仙女好累阅读 382评论 0 1