缓动函数与关键帧动画

缓动函数与关键帧动画

缓动函数指定动画效果在执行时的速度,使其看起来更加真实。

现实物体照着一定节奏移动,并不是一开始就移动很快的。当我们打开抽屉时,首先会让它加速,然后慢下来。当某个东西往下掉时,首先是越掉越快,撞到地上后回弹,最终才又碰触地板。

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. 缓动函数只是起到根据初值与结束值计算中间值的作用,我们需要将这些中间值设置进关键帧动画中才能够起到效果.







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值