版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abc6368765/article/details/81878978
首先是效果图:demo下载
- 首先把所有需要用到的帧动画素材添加到项目中,然后是把这些帧动画素材添加到NSMutableArray中,为ImageView设置animationImages属性,具体代码如下:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageAnim;
- (IBAction)startAnim:(UIButton *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// 执行动画的方法
- (void)startAnimating:(int)count picName:(NSString *)picName
{
// 如果当前图片框正在执行动画, 那么直接return, 什么都不做(没有开启一个新动画)
if (self.imageAnim.isAnimating) {
return;
}
// 1. 把图片加载到数组中
// 0.动态加载图片到一个NSArray中
NSMutableArray * picArrays = [NSMutableArray array];
for(int i=0; i<count; i++){
NSString * name = [NSString stringWithFormat:@"%@_%02d.jpg",picName,i];
// 根据图片名称加载图片
// 通过imageNamed: 这种方式加载图片, 加载好的图片会一直保存写在内存中, 不会释放.这样下次如果再使用同样的图片的时候就不需要再重新加载了, 因为内存里面已经有了。缺点就是: 如果加载了大量的图片, 那么这些图片会一直保留在内存中,导致应用程序占用内存过大(这就叫缓存)
// 使用这种方式加载图片, 加载起来的图片即便没有强类型指针引用也不会销毁(会被缓存)
UIImage *imgCat = [UIImage imageNamed:name];
// 使用下面这种方式加载的图片, 只要没有强类型指针引用就会被销毁了
// 解决: 换一种加载图片的方式, 不要使用缓存
// 获取图片的完成的路径
// NSString *path = [[NSBundle mainBundle] pathForResource:@"drink_11.jpg" ofType:nil];
// NSString *path = [[NSBundle mainBundle] pathForResource:@"pic.plist" ofType:nil];
// 这里的参数不能再传递图片名称了, 这里需要传递一个图片的完整路径
// UIImage *imgCat = [UIImage imageWithContentsOfFile:path];
// 把图片加载到数组中
[picArrays addObject:imgCat];
}
self.imageAnim.animationImages = picArrays;
self.imageAnim.animationDuration = self.imageAnim.animationImages.count * 0.1;
self.imageAnim.animationRepeatCount = 1;
[self.imageAnim startAnimating];
}
- (IBAction)startAnim:(UIButton *)sender {
switch (sender.tag) {
case 10:
[self startAnimating:81 picName:@"drink"];
break;
case 20:
[self startAnimating:13 picName:@"cymbal"];
break;
case 30:
[self startAnimating:40 picName:@"eat"];
break;
case 40:
[self startAnimating:24 picName:@"pie"];
break;
case 50:
[self startAnimating:34 picName:@"stomach"];
break;
case 60:
[self startAnimating:56 picName:@"scratch"];
break;
default:
break;
}
}
@end