IOS开发-UIView之动画效果的实现方法

2016-08-20  本文已影响0人  起个名字太费劲

一、使用UIView类实现动画

基本写法,代码必须放在Begin和Commit之间:

[UIView beginAnimations:nil context:nil]; // 开始动画
// Code...
[UIView commitAnimations]; // 提交动画

简单例子:

[UIView beginAnimations:nil context:nil]; // 开始动画
[UIView setAnimationDuration:10.0]; // 动画时长

/**
 *  图像向下移动
 */
CGPoint point = _imageView.center;
point.y += 150;
[_imageView setCenter:point];

[UIView commitAnimations]; // 提交动画

同时运行多个动画效果:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
[_imageView setAlpha:0.0];
[UIView commitAnimations];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
CGPoint point = _imageView.center;
point.y += 150;
[_imageView setCenter:point];
[UIView commitAnimations];

以上代码实现的动画效果为( 同时执行 ):

1、图像向下平移150像像

2、设置图像透明度为0。

指定上下文:

CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationDuration:2.0];
[_imageView setAlpha:0];
[UIView commitAnimations];

UIGraphicsGetCurrentContext():获取当前视图的上下文

其它方法及属性:

// 开始动画
+ (void)beginAnimations:(NSString *)animationID context:(void *)context;

// 提交动画
+ (void)commitAnimations; 

// 设置动画曲线,默认是匀速进行:
+ (void)setAnimationCurve:(UIViewAnimationCurve)curve;

// 设置动画时长:
+ (void)setAnimationDuration:(NSTimeInterval)duration;
 
// 默认为YES。为NO时跳过动画效果,直接跳到执行后的状态。
+ (void)setAnimationsEnabled:(BOOL)enabled;

// 设置动画延迟执行(delay:秒为单位):
+ (void)setAnimationDelay:(NSTimeInterval)delay;
 
// 动画的重复播放次数
+ (void)setAnimationRepeatCount:(float)repeatCount;

// 如果为YES,逆向(相反)动画效果,结束后返回动画逆向前的状态; 默认为NO:
+ (void)setAnimationRepeatAutoreverses:(BOOL)repeatAutoreverses;

// 设置动画代理:
+ (void)setAnimationDelegate:(id)delegate;
 
// 动画将要开始时执行方法××(必须要先设置动画代理):
+ (void)setAnimationWillStartSelector:(SEL)selector;

// 动画已结束时执行方法××(必须要先设置动画代理):
+ (void)setAnimationDidStopSelector:(SEL)selector;

/**
 *  设置动画过渡效果
 *
 *  @param transition 动画的过渡效果
 *  @param view 过渡效果作用视图
 *  @param cache 如果为YES,开始和结束视图分别渲染一次并在动画中创建帧;否则,视图将会渲染每一帧。例如,你不需要在视图转变中不停的更新,你只需要等到转换完成再去更新视图。
 */
+ (void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)cache;

// 删除所有动画层
// 注意:层指的是layout,例:[_imageView.layer removeAllAnimations];
- (void)removeAllAnimations;

二、使用UIView的动画块代码:

方法一:

[UIView animateWithDuration:4.0 // 动画时长
                 animations:^{
                     // code
                 }];

方法二:

UIView animateWithDuration:4.0 // 动画时长
         animations:^{
           // code...
         }
         completion:^(BOOL finished) {
           // 动画完成后执行
           // code...
         }];

方法三:

[UIView animateWithDuration:4.0 // 动画时长
            delay:2.0 // 动画延迟
          options:UIViewAnimationOptionCurveEaseIn // 动画过渡效果
         animations:^{
           // code...
         }
         completion:^(BOOL finished) {
           // 动画完成后执行
           // code...
         }];
上一篇 下一篇

猜你喜欢

热点阅读