一个简简单单的视图小动画
#import "RootViewController.h"
@interface RootViewController ()
// 声明一个imageView
@property (nonatomic, retain) UIImageView *imageView;
// 声明一个保存初始的中心点
@property (nonatomic, assign) CGPoint center;
// 声明一个保存初始frame的属性
@property (nonatomic, assign)CGRect frame;
记得添加方法
- (void)viewDidLoad {
[self addSubViews];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
布局
- (void)addSubViews
{
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
self.imageView.backgroundColor = [UIColor blueColor];
[self.view addSubview:self.imageView];
[_imageView release];
// 保存一下中心点
_center = self.imageView.center;
_frame = self.imageView.frame;
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake(100, 230, 100, 30);
button.backgroundColor = [UIColor cyanColor];
[button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}
实现Button的点击方法
// 点击方法
- (void)actionButton:(id)button
{
// UIView动画
// 特点: 全是类方法调用 开始与结束之间的部分 是动画改变的部分
// 动画大小 位置 颜色 透明度 等
// 动画开始
// 参数1:名字 标识符
// 参数2:携带的参数 可以为空
[UIView beginAnimations:@"MyAnimations" context:nil];
// 设置动画
// 设置动画时间 在多少秒内 完结动画
[UIView setAnimationDuration:1];
// 还可以设置 延迟多少秒开始
[UIView setAnimationDelay:0];
// 设置反转
[UIView setAnimationRepeatAutoreverses:YES];
// 设置代理
[UIView setAnimationDelegate:self];
// 设置代理方法
[UIView setAnimationWillStartSelector:@selector(actionWillStart)];
[UIView setAnimationDidStopSelector:@selector(actionDidStop)];
// 设置速度曲线
[UIView setAnimationCurve: UIViewAnimationCurveEaseIn];
// 设置循环次数
[UIView setAnimationRepeatCount:3];
// 设置持续执行动画
[UIView setAnimationBeginsFromCurrentState:YES];
// 添加动画 改变大小位置
self.imageView.center = CGPointMake(300, 300);
// 改变颜色
self.imageView.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
// 改变透明度
self.imageView.alpha = 0;
// 改变大小
CGRect frame = self.imageView.frame ;
frame.size = CGSizeMake(200, 200);
self.imageView.frame = frame;
// 动画提交
[UIView commitAnimations];
}
实现UIView代理方法
- (void)actionWillStart
{
NSLog(@"动画开始");
}
- (void)actionDidStop
{
NSLog(@"动画结束");
// 复原初始的位置
self.imageView.center = self.center;
self.imageView.alpha = 1;
self.imageView.frame = self.frame;
}