1.“懒加载”和plist文件的加载
将属性放在get方法中初始化的方式,称为“懒加载”\”延迟加载”
<span style="font-size:18px;">- (NSArray *)imageData
{
if (_imageData == nil) { // 从未初始化
// 初始化数据
// File : 全路径
// NSBundle : 一个NSBundle代表一个文件夹
// 利用mainBundle就可以访问软件资源包中的任何资源
NSBundle *bundle = [NSBundle mainBundle];
// 获得imageData.plist的全路径
NSString *path = [bundle pathForResource:@"imageData" ofType:@"plist"];
//加载plist文件
_imageData = [NSArray arrayWithContentsOfFile:path];
}
return _imageData;
}</span>
2.UIImageView帧动画相关属性和方法
@property(nonatomic,copy)NSArray *animationImages;
需要播放的序列帧图片数组(里面都是UIImage对象,会按顺序显示里面的图片)
@property(nonatomic)NSTimeInterval animationDuration;
帧动画的持续时间
@property(nonatomic)NSInteger animationRepeatCount;
帧动画的执行次数(默认是无限循环)
- (void)startAnimating;
开始执行帧动画
- (void)stopAnimating;
停止执行帧动画
- (BOOL)isAnimating;
是否正在执行帧动画
3.UIImage的2种加载方式
方式一:有缓存(图片所占用的内存会一直停留在程序中)
+ (UIImage *)imageNamed:(NSString *)name;
name是图片的文件名
方式二:无缓存(图片所占用的内存会在一些特定操作后被清除)
+ (UIImage *)imageWithContentsOfFile:(NSString*)path
- (id)initWithContentsOfFile:(NSString*)path;
path是图片的全路径
4.UIImageView播放动画实例
<span style="font-size:18px;">/** 播放动画 */
- (void)runAnimationWithCount:(int)count name:(NSString *)name
{
//判断是否为图片序列
if (self.tom.isAnimating) return;
// 1.加载所有的动画图片,将图片序列放入数组中,依次取出
NSMutableArray *images = [NSMutableArray array];
for (int i = 0; i<count; i++) {
// 计算文件名
NSString *filename = [NSString stringWithFormat:@"%@_%02d.jpg", name, i];
// 加载图片
// imageNamed: 有缓存(传入文件名)
// UIImage *image = [UIImage imageNamed:filename];
// imageWithContentsOfFile: 没有缓存(传入文件的全路径)
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:filename ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:path];
// 添加图片到数组中
[images addObject:image];
}
self.tom.animationImages = images;
// 2.设置播放次数(1次)
self.tom.animationRepeatCount = 1;
// 3.设置播放时间
self.tom.animationDuration = images.count * 0.05;
[self.tom startAnimating];
// 4.动画放完1秒后清除内存
CGFloat delay = self.tom.animationDuration + 1.0;
//调用setter方法,参数(withObject)为空
//相当于在setter方法中调用[self.tom setAnimationImages:nil];
[self.tom performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:delay];
}</span>