import “ViewController.h”
@interface ViewController ()
@property(nonatomic,retain)UIImageView *imageView;
@end
@implementation ViewController
- (void)dealloc
{
self.imageView = nil;
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
UIImage *image = [UIImage imageNamed:@"Zombie0.tiff"];
self.imageView = [[UIImageView alloc]initWithImage:image];
_imageView.frame = CGRectMake(60, 60, 160, 240);
[self.view addSubview:_imageView];
[_imageView release];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.backgroundColor = [UIColor brownColor];
button.frame = CGRectMake(140, 360, 40, 30);
[button setTitle:@"开始" forState:UIControlStateNormal];
[self.view addSubview:button];
//添加关联事件
[button addTarget:self action:@selector(controlAnimation:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)controlAnimation:(UIButton *)sender{
//取出button上的title
NSString *title = [sender titleForState:UIControlStateNormal];
//判断title是否和@"开始"相同,相同则开始动画,并修改标题为@"停止",如果不相同,则停止动画,并修改标题为@"开始"
if ([title isEqualToString:@"开始"]) {
[self aninationWithImageName:@"Zombie"andImageCount:21];
[sender setTitle:@"停止" forState:UIControlStateNormal];
} else {
[_imageView stopAnimating];
[sender setTitle:@"开始" forState:UIControlStateNormal];
}
}
(void)aninationWithImageName:(NSString *)names andImageCount:(int )count{
if (_imageView.isAnimating) {
return;
}
NSMutableArray *imageArray = [NSMutableArray array];for (int i = 0; i < count; i++) {
NSString *name = [NSString stringWithFormat:@"%@%d.tiff",names,i]; UIImage *image = [UIImage imageNamed:name]; [imageArray addObject:image]; _imageView.animationImages = imageArray; _imageView.animationDuration = imageArray.count * 0.03; _imageView.animationRepeatCount = 0; [_imageView startAnimating];
}
}