缓动函数与关键帧动画
缓动函数指定动画效果在执行时的速度,使其看起来更加真实。
现实物体照着一定节奏移动,并不是一开始就移动很快的。当我们打开抽屉时,首先会让它加速,然后慢下来。当某个东西往下掉时,首先是越掉越快,撞到地上后回弹,最终才又碰触地板。
iOS开发中的关键帧动画需要在给定初值与结束值之间插入中间值,这就是iOS开发中的关键帧动画.
以下使用关键帧动画配合缓动函数实现时钟秒表摆动时的震动效果.
//
// RootViewController.m
//
// Copyright (c) 2014年 Y.X. All rights reserved.
//
#import "RootViewController.h"
#import "YXGCD.h"
#import "YXEasing.h"
@interface RootViewController ()
@property (nonatomic, strong) GCDTimer *timer;
@end
// 将角度转换为弧度
#define DEGREES_TO_RADIANS(d) ((d) * M_PI / 180.f)
@implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 显示参考用的view
UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 300, 300)];
showView.layer.borderWidth = 1.f;
showView.layer.cornerRadius = 150.f;
showView.layer.borderColor = [UIColor redColor].CGColor;
showView.center = self.view.center;
[self.view addSubview:showView];
// 新建layer
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor blackColor].CGColor;
// 重置锚点
layer.anchorPoint = CGPointMake(0.f, 0.f);
// 设置layer的frame值(在showView正中间摆放)
layer.frame = CGRectMake(showView.middleX, showView.middleY, 1, 150);
// 添加进showView中
[showView.layer addSublayer:layer];
// 定时器
_timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
[_timer event:^{
static int i = 1;
// 计算好起始值,结束值
CGFloat oldValue = DEGREES_TO_RADIANS((360/60.f) * i++);
CGFloat newValue = DEGREES_TO_RADIANS((360/60.f) * i);
// 关键帧动画
CAKeyframeAnimation *animation = \
[CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
// 设置值
[animation setValues:[YXEasing calculateFrameFromValue:oldValue
toValue:newValue
func:ElasticEaseOut
frameCount:500]];
// 设置持续时间
animation.duration = 0.5f;
// 每秒增加的角度(设定结果值,在提交动画之前执行)
layer.transform = \
CATransform3DMakeRotation(newValue, 0.0, 0.0, 1.0);
// 提交动画
[layer addAnimation:animation forKey:nil];
} timeInterval:NSEC_PER_SEC];
[_timer start];
}
@end
效果如下(其实,真机效果上更好,转换为gif图片后欠佳-_-!!):
核心代码:
小结:
1. 关键帧动画与基本动画类型没有本质的区别,要说区别,那就是基本动画类型能做的事情,关键帧动画全部都能做,关键帧动画能设定的值更多.
2. 缓动函数只是起到根据初值与结束值计算中间值的作用,我们需要将这些中间值设置进关键帧动画中才能够起到效果.