UI:UIView动画事务

简介

  • 日常开发中常使用动画,恰当地使用动画有助于提高用户体验。
  • UIView动画事务提供了大量简单的接口来实现种类繁多的动画效果。
  • UIView动画事务多用于执行隐式动画:
    frame:设置视图大小及位置
    bounds:设置视图矩形大小
    center:设置视图中心点位置
    transform:设置视图的纺射变幻属性(缩放、旋转)
    alpha:设置视图的透明度

UIView动画事务基本要素

  • 持续时间:Duration,描述了动画执行的总时间。
  • 线性规律:Curve,描述了动画的执行方式,展示的效果。
  • 动画类型:通过改变视图属性,生成隐式动画效果。
  • 回调方法:动画委托方法或选取器方法,可以监视动画执行状态,并在相应状态执行自定义操作。
  • 其他配置:UIView动画事务提供了更多的配置接口,使动画效果更多样化。

UIView动画事务的初始化及配置

  • 一般方法配置动画事务
+(void)beginAnimations:(NSString *)animationID context:(void *)context;
+(void)commitAnimations;

[UIView beginAnimations:@"alpha" context:nil];

    // 动画事务配置代码:
    // 持续时间;
    // 线性规律;
    // 重复次数;
    // ......

[UIView commitAnimations];
  • 使用block代码块实现动画事务
+(void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations;
[UIView animateWithDuration:1.0 animations:^{

        // 动画事务配置代码:
        // 持续时间;
        // 线性规律;
        // 重复次数;
        // ......

}];

UIView转场动画及委托回调配置

  • +(void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)cache;
    UIViewAnimationTransition:
    UIViewAnimationTransitionNone:无转场动画类型
    UIViewAnimationTransitionFlipFromLeft:页面从左向右翻转
    UIViewAnimationTransitionFlipFromRight:页面从右向左翻转
    UIViewAnimationTransitionCurlUp:向上翻页
    UIViewAnimationTransitionCurlDown:向下翻页
设置委托
+ (void)setAnimationDelegate:(id)delegate;
动画开始回调方法
+ (void)setAnimationWillStartSelector:(SEL)selector;
动画结束回调方法
+ (void)setAnimationDidStopSelector:(SEL)selector;
动画回调方法声明(以动画结束回调为例)
// animationID:标识符,用于判断当前结束的动画是哪一个
// finished:动画结束
// context:上下文

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context;
+ (void)setAnimationDidStopSelector:(SEL)selector;
动画事务block生成回调方法
[UIView animateWithDuration:1.0 animations:^{
    // 配置动画
} completion:^(BOOL finished) {
    // 动画回调
}];
  • Tips:
    如果需要实现组合动画,对于动画事务一般生成方法,需要设置代理,并且声明回调方法,在回调方法中根据 AnimationId 判断当前结束的是哪一个动画,然后根据需求执行下一个动画方法;而对于动画事务block生成方法,无需声明回调方法,直接在 completion 块中执行动画结束后的操作即可(即执行下一个动画)。

一般动画事务生成方法

#import "UIViewAnimationsViewController.h"

// 动画持续时间
static NSTimeInterval const animationDuration = 1.0;

// animation ids
static NSString *const kUIViewAnimationTypePosition = @"position";
static NSString *const kUIViewAnimationTypeScale    = @"scale";
static NSString *const kUIViewAnimationTypeRotate   = @"rotate";
static NSString *const kUIViewAnimationTypeColor    = @"color";
static NSString *const kUIViewAnimationTypeAlpha    = @"alpha";
static NSString *const kUIViewAnimationTypeEnd      = @"end";

@interface UIViewAnimationsViewController ()

{
    UIView *_animationsView;
}

@property (nonatomic, copy) UIView *animationsView; /**< 动画视图 */

- (void)initializeUserInterface; /**< 初始化用户界面 */

// 1、UIView动画事务一般生成

- (void)positionAnimation;
- (void)scaleAnimation;
- (void)rotateAnimation;
- (void)colorAnimation;
- (void)alphaAnimation;
- (void)endAnimations;

// 动画结束回调方法
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context;

@end

@implementation UIViewAnimationsViewController

- (void)dealloc
{
    [_animationsView release]; _animationsView = nil;

    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
}

#pragma mark *** Initialize methods ***

- (instancetype)init {
    if (self = [super init]) {
        self.title = @"ViewAnimations";
    }
    return self;
}

- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.animationsView];


    // 添加点击手势,触发动画
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToGesture:)];
    [_animationsView addGestureRecognizer:tap];

    [tap release];


}

#pragma mark *** UIView动画事务一般生成 ***

/**
 * 动画基本要素:持续时间,线性规律,动画类型,回调方法,其他配置
 */

- (void)positionAnimation {
    // 一般动画事务生成方法
    [UIView beginAnimations:kUIViewAnimationTypePosition context:nil];
    // 持续时间
    [UIView setAnimationDuration:animationDuration];
    // 线性规律
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    // 动画回调
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    // 其他配置
    // [UIView setAnimationRepeatCount:HUGE_VAL]; // 动画重复次数
    // [UIView setAnimationRepeatAutoreverses:YES]; // 设置动画是否方向执行

    // 动画类型
    _animationsView.center = self.view.center;

    // 提交动画
    [UIView commitAnimations];
}

- (void)scaleAnimation {
    [UIView beginAnimations:kUIViewAnimationTypeScale context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    // 动画类型
    // 缩放、旋转动画使用transform属性
    // _animationView.transform = CGAffineTransformScale(_animationView.transform, 1.5, 1.5);
    _animationsView.transform = CGAffineTransformMakeScale(1.5, 1.5);
    [UIView commitAnimations];
}

- (void)rotateAnimation {
    [UIView beginAnimations:kUIViewAnimationTypeRotate context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    // 动画类型
    /*
     * M_PI:表示π,180度的弧度表示
     * M_PI_2:M_PI / 2
     * M_PI_4:M_PI / 4
     * CGAffineTransformMake...:新生成一个变幻属性,覆盖之前的.
     * CGAffineTransform...:在视图之前变幻属性的基础之上再进行变幻
     */
    _animationsView.transform = CGAffineTransformRotate(_animationsView.transform, M_PI_2);
    [UIView setAnimationRepeatCount:HUGE_VAL];

    [UIView commitAnimations];
}

- (void)colorAnimation {
    [UIView beginAnimations:kUIViewAnimationTypeColor context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    _animationsView.backgroundColor = [UIColor redColor];

    [UIView commitAnimations];
}

- (void)alphaAnimation {
    [UIView beginAnimations:kUIViewAnimationTypeAlpha context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    _animationsView.alpha = 0.5;

    [UIView commitAnimations];
}

- (void)endAnimations {
    [UIView beginAnimations:kUIViewAnimationTypeEnd context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    // 同一动画事务多个动画同时执行

    /*
     * UIView动画事务转场动画:
     * UIViewAnimationTransitionCurlUp     上翻页效果
     * UIViewAnimationTransitionCurlDown   下翻页效果
     */

    _animationsView.backgroundColor = [UIColor blackColor];
    _animationsView.alpha = 1;
    _animationsView.center = CGPointMake(CGRectGetMinX(self.view.bounds) + CGRectGetMidX(_animationsView.bounds),
                                         CGRectGetMinY(self.view.bounds) + CGRectGetMidY(_animationsView.bounds) + 64);
    // CGAffineTransformIdentity:将视图的transform属性重置,清除任何放射变幻属性 *
    _animationsView.transform = CGAffineTransformIdentity;

    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:_animationsView cache:NO];
    [UIView commitAnimations];

}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([animationID isEqualToString:kUIViewAnimationTypePosition]) {
        [self scaleAnimation];
    }else if ([animationID isEqualToString:kUIViewAnimationTypeScale]){
        [self rotateAnimation];
    }else if ([animationID isEqualToString:kUIViewAnimationTypeRotate]){
        [self colorAnimation];
    }else if ([animationID isEqualToString:kUIViewAnimationTypeColor]){
        [self alphaAnimation];
    }else if ([animationID isEqualToString:kUIViewAnimationTypeAlpha]){
        [self endAnimations];
    }
}
#pragma mark *** Gestures ***
- (void)respondsToGesture:(UITapGestureRecognizer *)gesture {
    NSLog(@"%@", NSStringFromSelector(_cmd));

    // 1、UIView动画一般事务
    [self positionAnimation];
}

#pragma mark *** Getters ***
- (UIView *)animationsView {
    if (!_animationsView) {
        _animationsView = [[[UIView alloc] init] autorelease];
        _animationsView.bounds = CGRectMake(0, 0, 160, 160);
        _animationsView.center = CGPointMake(CGRectGetMidX(_animationsView.bounds), CGRectGetMidY(_animationsView.bounds) + 64);
        _animationsView.backgroundColor = [UIColor blackColor];
    }
    return _animationsView;
}


@end
Block实现

#import "UIViewAnimationsViewController.h"

static NSTimeInterval const animationDuration = 1.0;

@interface UIViewAnimationsViewController ()

{
    UIView *_animationsView;
}

@property (nonatomic, copy) UIView *animationsView; /**< 动画视图 */

- (void)initializeUserInterface; /**< 初始化用户界面 */

// 1、UIView动画事务block生成
- (void)positionAnimationBlock;
- (void)scaleAnimationBlock;
- (void)rotateAnimationBlock;
- (void)colorAnimationBlock;
- (void)alphaAnimationBlock;
- (void)endAnimationsBlock;

@end

@implementation UIViewAnimationsViewController

- (void)dealloc
{
    [_animationsView release]; _animationsView = nil;

    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
}

#pragma mark *** Initialize methods ***

- (instancetype)init {
    if (self = [super init]) {
        self.title = @"ViewAnimations";
    }
    return self;
}

- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.animationsView];


    // 添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToGesture:)];
    [_animationsView addGestureRecognizer:tap];

    [tap release];


}

#pragma mark *** UIView动画事务block生成 ***

- (void)positionAnimationBlock {
    /**
     * animateWithDuration:持续时间
     * delay:延迟
     * options:可选,配置线性规律
     * animations:动画类型
     * completion:动画回调
     */
    [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        // 处理动画类型及基本配置
        _animationsView.center = self.view.center;
    } completion:^(BOOL finished) {
        // 动画执行完后回调方法
        [self scaleAnimationBlock];
    }];
}

- (void)scaleAnimationBlock {
    [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        //        _animationView.transform = CGAffineTransformScale(_animationView.transform, 1.5, 1.5);
        _animationsView.transform = CGAffineTransformMakeScale(1.5, 1.5);
    } completion:^(BOOL finished) {
        [self rotateAnimationBlock];
    }];
}

- (void)rotateAnimationBlock {
    [UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptionCurveLinear) animations:^{
        _animationsView.transform = CGAffineTransformRotate(_animationsView.transform, M_PI);
    } completion:^(BOOL finished) {
        [self colorAnimationBlock];
    }];
}

- (void)colorAnimationBlock {
    [UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptionCurveLinear) animations:^{
        _animationsView.backgroundColor = [UIColor redColor];
    } completion:^(BOOL finished) {
        [self alphaAnimationBlock];
    }];
}

- (void)alphaAnimationBlock {
    [UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptionCurveLinear) animations:^{
        _animationsView.alpha = 0.5;
    } completion:^(BOOL finished) {
        [self endAnimationsBlock];
    }];
}

- (void)endAnimationsBlock {
    [UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptionCurveLinear) animations:^{
        _animationsView.center = CGPointMake(CGRectGetMinX(self.view.bounds) + CGRectGetMidX(_animationsView.bounds),
                                             CGRectGetMinY(self.view.bounds) + CGRectGetMidY(_animationsView.bounds) + 64);
        _animationsView.backgroundColor = [UIColor blackColor];
        _animationsView.alpha = 1;
        _animationsView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {

    }];
}
#pragma mark *** Gestures ***
- (void)respondsToGesture:(UITapGestureRecognizer *)gesture {
    NSLog(@"%@", NSStringFromSelector(_cmd));

    // 1、UIView动画一般事务
    [self positionAnimationBlock];
}

#pragma mark *** Getters ***
- (UIView *)animationsView {
    if (!_animationsView) {
        _animationsView = [[[UIView alloc] init] autorelease];
        _animationsView.bounds = CGRectMake(0, 0, 160, 160);
        _animationsView.center = CGPointMake(CGRectGetMidX(_animationsView.bounds), CGRectGetMidY(_animationsView.bounds) + 64);
        _animationsView.backgroundColor = [UIColor blackColor];
    }
    return _animationsView;
}


@end

UIImageView动画

  • UIImageView是图片展示视图,除了展示图片功能之外,也可以用于实现动画效果。

  • 动画配置
    animationImages:设置动画图片数组
    animationDuration:设置动画持续时长
    animationRepeatCount:设置动画重复次数,默认为0无限次重复

  • 常用方法
    开始执行动画
    - (void)startAnimating;

    结束执行动画
    - (void)stopAnimating;
    

UIImageView动画代码案例

  • 初始化UIImageView动画
- (void)initializeImageAnimations {
    // 持续时间
    _imageAnimationsView = 5.0;
    // 图片数据源,_images为存储UIImage对象的数组。
    _imageAnimationsView = _images;
    // 重复次数
    _imageAnimationsView = 0;
    // 开始动画
    [_imageAnimationsView startAnimating];
}
  • 触摸拖动_imageAnimationsView视图方法
// 触摸移动
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 根据移动的轨迹移动图片视图
    UITouch *touch = [touches anyObject];
    if (touch.view == _imageAnimationsView) {
        // 获取上一个点
        CGPoint previousLocation = [touch previousLocationInView:_imageAnimationsView];
        // 获取当前点
        CGPoint currentLocation = [touch locationInView:_imageAnimationsView];
        // 获取偏移
        CGPoint offset = CGPointMake(currentLocation.x - previousLocation.x, currentLocation.y - previousLocation.y);

        // 更新图片视图中心点
        _imageAnimationsView.center = CGPointMake(_imageAnimationsView.center.x + offset.x, _imageAnimationsView.center.y + offset.y);

    }
}

动画事件

有时需要在某一个视图执行动画的过程中(比如位置移动)实现点击效果,如果通过添加手势的方式,会发现,即使开启了用户交互userInteractionEnabled也不会达到预期的效果,这是由于UIView动画事务执行的是隐式动画,因此不能通过手势的方式,而应该通过触摸的方式处理逻辑,此处模拟动画在移动过程中实现点击效果,animatingView为添加UIView动画事务移动的的动画。直接上关键代码;

#pragma mark *** Touches ***

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    CGPoint location = [touch locationInView:self.view];

    if ([self.animatingView.layer.presentationLayer hitTest:location]) {

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,946评论 4 60
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,066评论 5 13
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,421评论 6 30
  • 今年放假我跟着小博士夏令营来到了北戴河,游览了奥林匹克大道公园、秦皇岛野生动物园、新奥海底世界、集发农业观光园和乐...
    一疯上神阅读 629评论 0 0
  • “我的小爪爪可真美” 用脚蹬我,“你快起开,别抢镜啊” “请开始你的抓拍” “我要站着拍” “别盯着人家看,人家会...
    夕夏星辰阅读 205评论 0 0