一個簡簡單單的視圖小動畫
#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;
}