效果圖
需求:
- 純代碼實現(xiàn),界面布局(兩個按鈕,一個圖片)
- 實現(xiàn)按鈕的對應功能("站立"和"大招"的動畫)
代碼(部分):
-(void)layoutUI{
//UIImageView
self.imgViewTemp = [[UIImageView alloc]init];
self.imgViewTemp.frame = CGRectMake(20, 20, 341, 600);
self.imgViewTemp.backgroundColor = [UIColor redColor];
//保存源圖片尺寸,靠左下角對齊!
self.imgViewTemp.contentMode = UIViewContentModeBottomLeft;
UIButton * btnStand = [[UIButton alloc]initWithFrame:CGRectMake(100, 70, 40, 40)];
[btnStand setTitle:@"站立" forState:(UIControlStateNormal)];
[btnStand setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//正常狀態(tài)
//事件
[btnStand addTarget:self action:@selector(btnStandClick:) forControlEvents:(UIControlEventTouchDown)];
...
[self.view addSubview:self.imgViewTemp];
[self.view addSubview:btnStand];
[self.view addSubview:btnDazhao];
}
// 執(zhí)行動畫
-(void)btnStandClick:(UIButton *)send{
//將圖片存放在 NSMutableArray里面
NSMutableArray * standMArray = [NSMutableArray array];
for (int i=0; i<10; i++) {
NSString *str = [NSString stringWithFormat: @"stand_%d",i+1];
UIImage *imgTemp = [UIImage imageNamed:str];
[standMArray addObject: imgTemp];
}
/*
animationImages 是 NSArray<UIImage *>類型
NSArray<UIImage *>,表示animationImages是不可變數(shù)組,并且數(shù)組里面只能存放UIImage類型.
standMArray 是NSMutableArray類型,NSMutableArray繼承NSArray!
所以直接使用就可,self.imgViewTemp.animationImages = standMArray;不需要轉(zhuǎn)換(會自動轉(zhuǎn)換)!
當然,手動轉(zhuǎn)換也可以
NSArray *myArray = [standMArray copy];
self.imgViewTemp.animationImages = myArray; //顯示的動畫
*/
self.imgViewTemp.animationImages = standMArray;
self.imgViewTemp.animationRepeatCount = 4; // 執(zhí)行次數(shù)
[self.imgViewTemp startAnimating]; //開始動畫
}
重點
- contentMode 圖片顯示方式
- UIControlState 按鈕狀態(tài)
- addTarget 按鈕的事件
- animationImages - 動畫對象數(shù)組
animationRepeatCount - 動畫執(zhí)行次數(shù)
startAnimating -開始動畫