ViewController.h文件中:
1 @interface ViewController : UIViewController 2 3 @property (weak, nonatomic) IBOutlet UIImageView *tomImg; 4 - (IBAction)btnClick:(UIButton *)sender; 5 6 @end
ViewController.m文件中:
#import "ViewController.h" @interface ViewController () { NSDictionary *_dicPicResoure; // 记录图片分组的个数 } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 获取tom.plist的全路径 NSString *path = [[NSBundle mainBundle] pathForResource:@"tom" ofType:@"plist"]; // 根据文件路径加载字典 _dicPicResoure = [NSDictionary dictionaryWithContentsOfFile:path]; } - (IBAction)btnClick:(UIButton *)sender { // 如果正在播放,直接返回 if (_tomImg.isAnimating) { return; } // 取出按钮文字 NSString *prefixName = [sender titleForState:UIControlStateNormal]; // 获取图片数量 int count = [_dicPicResoure[prefixName] intValue]; // 调用播放动画方法 [self playWithPicCount:count andPrefixName:prefixName]; } - (void)playWithPicCount:(int)count andPrefixName:(NSString *)name { // 创建可变数组 存储图片对象 NSMutableArray *aryImg = [NSMutableArray array]; // 添加图片 for (int i = 0; i < count; ++i) { NSString *picName = [NSString stringWithFormat:@"%@_d.jpg", name, i]; // 加载数据(缓存) // UIImage *img = [UIImage imageNamed:picName]; NSString *path = [[NSBundle mainBundle] pathForResource:picName ofType:nil]; UIImage *img = [UIImage imageWithContentsOfFile:path]; [aryImg addObject:img]; } // 设置动画图片(有顺序) _tomImg.animationImages = aryImg; // 只播放一次 _tomImg.animationRepeatCount = 1; // 设置动画的持续时间 _tomImg.animationDuration = 0.1 * count; // 开始动画 [_tomImg startAnimating]; } @end
界面效果图:
时间: 2024-12-15 13:27:23