iOS 動畫 第九章 緩沖

//CALayer
    //[self mediaTimingTest];
    
    //UIView
    //[self viewEaseTest];
    
    //keyanimation ease
    //[self keyFrameAnimationEaseTest];
    
    //三次貝塞爾曲線
    //[self mediaTimingBezierTest];
    
    //緩沖函數(shù)的時鐘程序
    //[self clockViewAnimationTest];
    
    //基于關(guān)鍵幀的緩沖
    //[self ballBounceTest];

動畫速度

//velocity = change / time 對于這種恒定速度的動畫我們稱之為“線性步調(diào)”

緩沖函數(shù)

//CAMediaTimingFunction
//首先需要設(shè)置CAAnimation的timingFunction屬性嬉荆,是CAMediaTimingFunction類的一個對象捆探。如果想改變隱式動畫的計時函數(shù),同樣也可以使用CATransaction的+setAnimationTimingFunction:方法谎碍。
//這里有一些方式來創(chuàng)建CAMediaTimingFunction,最簡單的方式是調(diào)用+timingFunctionWithName:的構(gòu)造方法且警。這里傳入如下幾個常量之一:
//kCAMediaTimingFunctionLinear:線性步調(diào)對于那些立即加速并且保持勻速到達(dá)終點的場景會有意義
//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) {
        
    }];
}
 */

緩沖和關(guān)鍵幀動畫

//CAKeyframeAnimation有一個NSArray類型的timingFunctions屬性妈踊,我們可以用它來對每次動畫的步驟指定不同的計時函數(shù)娱局。但是指定函數(shù)的個數(shù)一定要等于keyframes數(shù)組的元素個數(shù)減一彰亥,因為它是描述每一幀之間動畫速度的函數(shù)。

- (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];
}

自定義緩沖函數(shù)

//CAMediaTimingFunction同樣有另一個構(gòu)造函數(shù)衰齐,一個有四個浮點參數(shù)的+functionWithControlPoints::::

三次貝塞爾曲線

//CAMediaTimingFunction函數(shù)的主要原則在于它把輸入的時間轉(zhuǎn)換成起點和終點之間成比例的改變任斋。
//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;
}

//那么對于我們自定義時鐘指針的緩沖函數(shù)來說废酷,我們需要初始微弱,然后迅速上升抹缕,最后緩沖到終點的曲線澈蟆,通過一些實驗之后,最終結(jié)果如下:
//[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;
    }
}

更加復(fù)雜的動畫曲線

//考慮一個橡膠球掉落到堅硬的地面的場景,不能用CAMediaTimingFunction來完成
//用CAKeyframeAnimation創(chuàng)建一個動畫歉嗓,然后分割成幾個步驟丰介,每個小步驟使用自己的計時函數(shù)
//使用定時器逐幀更新實現(xiàn)動畫

//基于關(guān)鍵幀的緩沖

- (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];
}

流程自動化

//自動把任意屬性動畫分割成多個關(guān)鍵幀
//用一個數(shù)學(xué)函數(shù)表示彈性動畫,使得可以對幀做便宜
//value = (endValue – startValue) × time + startValue;
//那么如果要插入一個類似于CGPoint鉴分,CGColorRef或者CATransform3D這種更加復(fù)雜類型的值哮幢,我們可以簡單地對每個獨立的元素應(yīng)用這個方法

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];
}

//羅伯特·彭納有一個網(wǎng)頁關(guān)于緩沖函數(shù)(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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市志珍,隨后出現(xiàn)的幾起案子橙垢,更是在濱河造成了極大的恐慌,老刑警劉巖伦糯,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柜某,死亡現(xiàn)場離奇詭異,居然都是意外死亡敛纲,警方通過查閱死者的電腦和手機喂击,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來淤翔,“玉大人翰绊,你說我怎么就攤上這事∨宰常” “怎么了监嗜?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長抡谐。 經(jīng)常有香客問我裁奇,道長,這世上最難降的妖魔是什么麦撵? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任刽肠,我火速辦了婚禮溃肪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘音五。我一直安慰自己乍惊,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布放仗。 她就那樣靜靜地躺著,像睡著了一般撬碟。 火紅的嫁衣襯著肌膚如雪诞挨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天呢蛤,我揣著相機與錄音惶傻,去河邊找鬼。 笑死其障,一個胖子當(dāng)著我的面吹牛银室,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播励翼,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蜈敢,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了汽抚?” 一聲冷哼從身側(cè)響起抓狭,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎造烁,沒想到半個月后否过,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡惭蟋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年苗桂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片告组。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡煤伟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出惹谐,到底是詐尸還是另有隱情持偏,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布氨肌,位于F島的核電站鸿秆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏怎囚。R本人自食惡果不足惜卿叽,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一桥胞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧考婴,春花似錦贩虾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至考杉,卻和暖如春策精,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背崇棠。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工咽袜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人枕稀。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓询刹,卻偏偏與公主長得像,于是被迫代替她去往敵國和親萎坷。 傳聞我的和親對象是個殘疾皇子凹联,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • >生活和藝術(shù)一樣,最美的永遠(yuǎn)是曲線食铐。--愛德華布爾沃-利頓 在第九章“圖層時間”中匕垫,我們討論了動畫時間和`CAMe...
    夜空下最亮的亮點閱讀 474評論 0 0
  • 生活和藝術(shù)一樣,最美的永遠(yuǎn)是曲線虐呻。 -- 愛德華布爾沃 - 利頓 在第九章“圖層時間”中象泵,我們討論了動畫時間和CA...
    雪_晟閱讀 477評論 0 0
  • 緩沖 生活和藝術(shù)一樣偶惠,最美的永遠(yuǎn)是曲線。 -- 愛德華布爾沃 - 利頓 在第九章“圖層時間”中朗涩,我們討論了動畫時間...
    方圓幾度閱讀 510評論 0 0
  • 本文轉(zhuǎn)載自:http://www.cocoachina.com/ios/20150105/10829.html 為...
    idiot_lin閱讀 458評論 0 0
  • 1 阿空15歲那年遇見了小晶忽孽。 在暑期補習(xí)班里,那個女孩留著短發(fā)谢床,臉上長著幾顆青春痘兄一。個子不高,長得也不出眾识腿,但眼...
    阿空12138閱讀 599評論 0 26