iOS开发UI篇----UI基础之Tom猫动画

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;


// 定义字典读取plist文件
@property (nonatomic, strong) NSDictionary *imageCountDict;

@end

@implementation ViewController

// 懒加载, 重写get方法
- (NSDictionary *)imageCountDict {
  if (nil == _imageCountDict) {
    // 获得plist的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"tom" ofType:@"plist"];
    
    // 读取plist中的数据
    _imageCountDict = [NSDictionary dictionaryWithContentsOfFile:path];
    
  }
  
  return _imageCountDict;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.

}

// 点击头部按钮
- (IBAction)didClickKnock:(id)sender {
  
  [self startAnimationWith:@"knockout"];
  
}

// 点击喝牛奶
- (IBAction)didClickDrink:(id)sender {
  
  [self startAnimationWith:@"drink"];
  
}

// 点击放屁
- (IBAction)didClickFart:(id)sender {
  
  [self startAnimationWith:@"fart"];
  
  
}


// 相同的代码放到一个方法里, 不同的变成参数
- (void)startAnimationWith:(NSString *)imageName {
  
  // 通过字典中的key 取得value也就是对应的image的数量
  NSString *countString = [self.imageCountDict objectForKey:imageName];
  
  // 转换为NSInteger
  NSInteger count = countString.integerValue;
  
  
  // 判断是否正在执行帧动画, 如果正在执行, 则return,就是,后面的代码不会再执行了
  if (self.imageView.isAnimating) {
    
    return;
  }
  
  // 1. 执行帧动画需要一个数组(数组元素都是image对象)
  NSMutableArray *imageArray = [NSMutableArray array];
  
  // 添加图片
  for (int i = 0; i < count; i++) {
    // 拼接image 名称
    NSString *tempImageName = [NSString stringWithFormat:@"%@_%02d.jpg",imageName,i];
    
    // 实例化image 对象
    // 如果使用imageNamed: 这个方法实例化图片, 会把实例化过的图片给缓存起来, 如果下次再去使用, 就不会再重新实例化
//    UIImage *image = [UIImage imageNamed:imageNmae];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:tempImageName ofType:nil];
  
    
    // 通过这种方式去加载图片的时候, 不会有缓存
    UIImage *image = [UIImage imageWithContentsOfFile: path];
    
    // 添加到数组
    [imageArray addObject:image];
  }
  
  // 把装满image对象的数组赋值给imageView
  self.imageView.animationImages = imageArray;
  
  // 2. 间隔的时间
  self.imageView.animationDuration = 3;
  
  // 3. 重复次数
  self.imageView.animationRepeatCount = 1;
  
  // 4. 开始动画
  [self.imageView startAnimating];
    
//    //释放内存
//    [self.imageView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageView.animationDuration + 1];
}

 

posted on 2015-09-03 21:10  DoNib  阅读(186)  评论(0编辑  收藏  举报

导航