IOS 简易动画 & 图片挪动实例

一 简易动画的用处

IOS 开发中,如果需要改变UI属性的值,比如坐标位置,为了用户有更好的体验,通常不会直接瞬间改变,而是加上动画效果,让过程有感知。

比如一个控件的 (x,y) 值本来是(100,100),如果需要改变为(0,0),通过简易动画可用达到慢慢平移的效果。


简易动画一般采用以下2种方式:

二 头尾式

//开始动画
[UIView beginAnimations:nil context:nil];

/** 需要执行动画的代码 **/

//设置动画效果(持续时间)
[UIView setAnimationDuration:2];//2秒
//提交动画
[UIView commitAnimations];


三 Block式

//0.5 是动画持续时间
[UIView animateWithDuration:0.5 animations:^{
    /** 需要执行动画的代码 **/
}];


四 代码块

实例:通过简易动画改变UIButton位置,UIButton 初始位置为屏幕中央,然后改变为(0,0)并添加上动画效果

//
//  ViewController.m
//  18Test


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //1.创建一个UI控件
    UIButton *btn = [[UIButton alloc]init];

    //2.设置名字
    [btn setTitle:@"click me!" forState:UIControlStateNormal];
    //3.设置背景颜色
    btn.backgroundColor=[UIColor redColor];
    
    //4.设置坐标
    CGFloat buttonW = 100;
    CGFloat buttonH = buttonW;
    CGFloat buttonX = (self.view.frame.size.width - buttonW) * 0.5;
    CGFloat buttonY = (self.view.frame.size.height - buttonH) * 0.5;
    btn.frame =  CGRectMake(buttonX,buttonY ,buttonW , buttonH);
    
    //5.添加到工程自带的view中
    [self.view addSubview:btn];
    
    
    /*=========== 测试动画效果 ============*/
    //6.调用头尾式动画
   //[self beginCommitAnimation];
    
    //7.调用头尾式动画
    [self blockAnimation];
}



/**
 *  头尾式动画
 */
-(void)beginCommitAnimation
{
    //1.开始动画
    [UIView beginAnimations:nil context:nil];
    //2.获取btn
    UIButton *btn = (UIButton *)[[self.view subviews]lastObject];
    //3.改变btn 坐标为 0,0
    [self changeLocation:btn];
  
    
    //4.动画效果设置 (持续时间)
    [UIView setAnimationDuration:2];//2秒
    //5.提交动画
    [UIView commitAnimations];
}



/**
 *  block式动画
 */
-(void)blockAnimation
{
    //1.获取button
    UIButton *btn = (UIButton *)[[self.view subviews]lastObject];
    //2.开始动画 设置为2秒动画持续时间
    [UIView animateWithDuration:20 animations:^{
        //3.改变btn 坐标位置
        [self changeLocation:btn];
    }];
}


/**
 *  改变UIButton 位置 方法
 *
 *  @param btn btn description
 */
-(void)changeLocation:(UIButton *)btn
{
    CGFloat buttonW = 100;
    CGFloat buttonH = buttonW;
    CGFloat buttonX = 0;
    CGFloat buttonY = buttonX;
    btn.frame =  CGRectMake(buttonX,buttonY ,buttonW , buttonH);
}

@end


原图与效果图

IOS 简易动画 & 图片挪动实例IOS 简易动画 & 图片挪动实例

你可能感兴趣的:(ios,动画)