iOS 动画 第九章 缓冲

//CALayer
    //[self mediaTimingTest];
    
    //UIView
    //[self viewEaseTest];
    
    //keyanimation ease
    //[self keyFrameAnimationEaseTest];
    
    //三次贝塞尔曲线
    //[self mediaTimingBezierTest];
    
    //缓冲函数的时钟程序
    //[self clockViewAnimationTest];
    
    //基于关键帧的缓冲
    //[self ballBounceTest];

动画速度

//velocity = change / time 对于这种恒定速度的动画我们称之为“线性步调”

缓冲函数

//CAMediaTimingFunction
//首先需要设置CAAnimation的timingFunction属性,是CAMediaTimingFunction类的一个对象。如果想改变隐式动画的计时函数,同样也可以使用CATransaction的+setAnimationTimingFunction:方法。
//这里有一些方式来创建CAMediaTimingFunction,最简单的方式是调用+timingFunctionWithName:的构造方法。这里传入如下几个常量之一:
//kCAMediaTimingFunctionLinear:线性步调对于那些立即加速并且保持匀速到达终点的场景会有意义
//kCAMediaTimingFunctionEaseIn:一个慢慢加速然后突然停止的方法
//kCAMediaTimingFunctionEaseOut:它以一个全速开始,然后慢慢减速停止
//kCAMediaTimingFunctionEaseInEaseOut:一个慢慢加速然后再慢慢减速的过程
//kCAMediaTimingFunctionDefault:个慢慢加速然后再慢慢减速的过程,加速和减速的过程都稍微有些慢

- (void)mediaTimingTest {
    colorLayer = [CALayer layer];
    colorLayer.frame = CGRectMake(0, 20, 100, 100);
    colorLayer.position = CGPointMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height / 2.0);
    colorLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:colorLayer];
}
/*
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //configure the transaction
    [CATransaction begin];
    [CATransaction setAnimationDuration:1.0];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    //set the position
    colorLayer.position = [[touches anyObject] locationInView:self.view];
    //commit transaction
    [CATransaction commit];
}
 */

UIView的动画缓冲

//UIViewAnimationOptionCurveEaseInOut
//UIViewAnimationOptionCurveEaseIn
//UIViewAnimationOptionCurveEaseOut
//UIViewAnimationOptionCurveLinear

- (void)viewEaseTest {
    containerView = [[UIView alloc] init];;
    containerView.frame = CGRectMake(0, 20, 100, 100);
    containerView.center = CGPointMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height / 2.0);
    containerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:containerView];
}
/*
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //perform the animation
    [UIView animateWithDuration:1.0
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         //set the position
                         containerView.center = [[touches anyObject] locationInView:self.view];
                     }
                     completion:^(BOOL finished) {
        
    }];
}
 */

缓冲和关键帧动画

//CAKeyframeAnimation有一个NSArray类型的timingFunctions属性,我们可以用它来对每次动画的步骤指定不同的计时函数。但是指定函数的个数一定要等于keyframes数组的元素个数减一,因为它是描述每一帧之间动画速度的函数。

- (void)keyFrameAnimationEaseTest {
    layerView = [[UIView alloc] init];
    layerView.frame = CGRectMake(0, 20, 300, 300);
    [self.view addSubview:layerView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor redColor];
    btn.frame = CGRectMake(0, 500, 200, 44);
    [btn addTarget:self action:@selector(keyFrameChangeColor) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    colorLayer = [CALayer layer];
    colorLayer.frame = CGRectMake(50.0f, 50.0f, 100.01, 100.0f);
    colorLayer.backgroundColor = [UIColor blueColor].CGColor;
    //add it to our view
    [layerView.layer addSublayer:colorLayer];
}

- (void)keyFrameChangeColor {
    //create a keyframe animation
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"backgroundColor";
    animation.duration = 2.0;
    animation.values = @[
                         (__bridge id)[UIColor blueColor].CGColor,
                         (__bridge id)[UIColor redColor].CGColor,
                         (__bridge id)[UIColor greenColor].CGColor,
                         (__bridge id)[UIColor blueColor].CGColor
                         ];
    //add timing function
    CAMediaTimingFunction *fn = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animation.timingFunctions = @[fn,fn,fn];
    //apply animation to layer
    [colorLayer addAnimation:animation forKey:nil];
}

自定义缓冲函数

//CAMediaTimingFunction同样有另一个构造函数,一个有四个浮点参数的+functionWithControlPoints::::

三次贝塞尔曲线

//CAMediaTimingFunction函数的主要原则在于它把输入的时间转换成起点和终点之间成比例的改变。
//CAMediaTimingFunction有一个叫做-getControlPointAtIndex:values:的方法,可以用来检索曲线的点,然后用UIBezierPath和CAShapeLayer来把它画出来

- (void)mediaTimingBezierTest {
    layerView = [[UIView alloc] init];
    layerView.frame = CGRectMake(0, 100, 300, 300);
    layerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:layerView];
    
    //create timing function
    CAMediaTimingFunction *function = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    //get control points
    CGPoint controlPoint1 = CGPointMake(0.0, 0.0f), controlPoint2 = CGPointMake(0.0, 0.0f);
    [function getControlPointAtIndex:1 values:(float *)&controlPoint1];
    [function getControlPointAtIndex:2 values:(float *)&controlPoint2];
    //create curve
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointZero];
    [path addCurveToPoint:CGPointMake(1, 1) controlPoint1:controlPoint1 controlPoint2:controlPoint2];
    
    //scale the path up to a reasonable size for display
    [path applyTransform:CGAffineTransformMakeScale(250, 250)];
    
    //create shape layer
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = CGRectMake(25, 25, 250, 250);
    shapeLayer.backgroundColor = [UIColor blueColor].CGColor;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 4.0f;
    shapeLayer.path = path.CGPath;
    [layerView.layer addSublayer:shapeLayer];
    
    //flip geometry so that 0,0 is in the bottom-left
    layerView.layer.geometryFlipped = YES;
}

//那么对于我们自定义时钟指针的缓冲函数来说,我们需要初始微弱,然后迅速上升,最后缓冲到终点的曲线,通过一些实验之后,最终结果如下:
//[CAMediaTimingFunction functionWithControlPoints:1 :0 :0.75 :1];

- (void)setAngle:(CGFloat)angle forHand:(UIView *)handView animated:(BOOL)animated
{
    //generate transform
    CATransform3D transform = CATransform3DMakeRotation(angle, 0, 0, 1);
    if (animated) {
        //create transform animation
        CABasicAnimation *animation = [CABasicAnimation animation];
        animation.keyPath = @"transform";
        animation.fromValue = [handView.layer.presentationLayer valueForKey:@"transform"];
        animation.toValue = [NSValue valueWithCATransform3D:transform];
        animation.duration = 0.5;
        animation.delegate = self;
        animation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:1 :0 :0.75 :1];
        //apply animation
        handView.layer.transform = transform;
        [handView.layer addAnimation:animation forKey:nil];
    } else {
        //set transform directly
        handView.layer.transform = transform;
    }
}

更加复杂的动画曲线

//考虑一个橡胶球掉落到坚硬的地面的场景,不能用CAMediaTimingFunction来完成
//用CAKeyframeAnimation创建一个动画,然后分割成几个步骤,每个小步骤使用自己的计时函数
//使用定时器逐帧更新实现动画

//基于关键帧的缓冲

- (void)ballBounceTest {
    containerView = [[UIView alloc] init];
    containerView.frame = CGRectMake(20.f, 64.0f, 300.0f, 300.0f);
    containerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:containerView];
    
    //add image view
    imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0.0, 0.0f, 30.0, 30.0f);
    imageView.image = [UIImage imageNamed:@"Star"];
    [containerView addSubview:imageView];
    
    //animate
    //[self starBounceAnimation];
    [self pointToLineAnimation];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //replay animation on tap
    //[self starBounceAnimation];
//    [self pointToLineAnimation];
    [self timerAnimation];
}


- (void)starBounceAnimation {
    //reset star to top of screen
    imageView.center = CGPointMake(150.0, 32);
    //create keyframe animation
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"position";
    animation.duration = 1.0;
    animation.delegate = self;
    animation.values = @[
                         [NSValue valueWithCGPoint:CGPointMake(150, 32)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 268)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 140)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 268)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 220)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 268)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 250)],
                         [NSValue valueWithCGPoint:CGPointMake(150, 268)]
                         ];
    animation.timingFunctions = @[
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseIn],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseIn],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseIn],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut],
                                  [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseIn]
                                  ];
    animation.keyTimes = @[@0.0, @0.3, @0.5, @0.7, @0.8, @0.9, @0.95, @1.0];
    imageView.layer.position = CGPointMake(150.0, 268);
    [imageView.layer addAnimation:animation forKey:nil];
}

流程自动化

//自动把任意属性动画分割成多个关键帧
//用一个数学函数表示弹性动画,使得可以对帧做便宜
//value = (endValue – startValue) × time + startValue;
//那么如果要插入一个类似于CGPoint,CGColorRef或者CATransform3D这种更加复杂类型的值,我们可以简单地对每个独立的元素应用这个方法

float interpolate (float from, float to, float time) {
    return (to - from) * time + from;
}

- (id)interpolateFromValue:(id)fromValue toValure:(id)toValue time:(float)time {
    if ([fromValue isKindOfClass:[NSValue class]]) {
        //get type
        const char  *type = [fromValue objCType];
        if (strcmp(type, @encode(CGPoint)) == 0) {
            CGPoint from = [fromValue CGPointValue];
            CGPoint to = [toValue CGPointValue];
            CGPoint result = CGPointMake(interpolate(from.x, to.x, time), interpolate(from.y, to.y, time));
            return [NSValue valueWithCGPoint:result];
        }
    }
    
    //provide safe default implementation
    return (time < 0.5)? fromValue:toValue;
}

- (void)pointToLineAnimation {
    //reset ball to top of screen
    imageView.center = CGPointMake(150, 32);
    //set up animation parameters
    NSValue *fromValue = [NSValue valueWithCGPoint:CGPointMake(150.0, 32)];
    NSValue *toValue = [NSValue valueWithCGPoint:CGPointMake(150.0, 268)];
    
    CFTimeInterval duration = 1.0;
    //generate keyframes
    NSInteger numFrames = duration * 60;
    NSMutableArray *frames = [NSMutableArray array];
    for (int i = 0; i < numFrames; i++) {
        float time = 1 / (float)numFrames * i;
        //apply easing
        time = bounceEaseOut(time);
        //add key frame
        [frames addObject:[self interpolateFromValue:fromValue toValure:toValue time:time]];
    }
    
    //create key frame animation
    CAKeyframeAnimation *animation  = [CAKeyframeAnimation animation];
    animation.keyPath = @"position";
    animation.delegate = self;
    animation.duration = 1.0;
    animation.values = frames;
    //apply animation
    [imageView.layer addAnimation:animation forKey:nil];
}

//罗伯特·彭纳有一个网页关于缓冲函数(http://www.robertpenner.com/easing)
float quadraticEaseInOut(float t)
{
    return (t < 0.5)? (2 * t * t): (-2 * t * t) + (4 * t) - 1;
}

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

推荐阅读更多精彩内容

  • >生活和艺术一样,最美的永远是曲线。--爱德华布尔沃-利顿 在第九章“图层时间”中,我们讨论了动画时间和`CAMe...
    夜空下最亮的亮点阅读 471评论 0 0
  • 生活和艺术一样,最美的永远是曲线。 -- 爱德华布尔沃 - 利顿 在第九章“图层时间”中,我们讨论了动画时间和CA...
    雪_晟阅读 474评论 0 0
  • 缓冲 生活和艺术一样,最美的永远是曲线。 -- 爱德华布尔沃 - 利顿 在第九章“图层时间”中,我们讨论了动画时间...
    方圆几度阅读 503评论 0 0
  • 本文转载自:http://www.cocoachina.com/ios/20150105/10829.html 为...
    idiot_lin阅读 454评论 0 0
  • 1 阿空15岁那年遇见了小晶。 在暑期补习班里,那个女孩留着短发,脸上长着几颗青春痘。个子不高,长得也不出众,但眼...
    阿空12138阅读 587评论 0 26