Tom猫实例效果(只弄了两个功能还是缺少图片的,其他功能雷同):
原谅我嫌弃照图片太麻烦,用文字代替了。
首先通过storybord把基本布局布置好,然后就是拖线写函数。下面附上代码:
#import "ViewController.h"
@interface ViewController ()
- (IBAction)drink;
@property (weak, nonatomic) IBOutlet UIImageView *imageViewCat;
- (IBAction)eat;
@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.
}
//喝牛奶动画
- (IBAction)drink {
[self startAnimation:81 picName:@"drink"];
[self creatPlay:@"p_drink_milk.wav"];
}
//吃东西动画
- (IBAction)eat {
[self startAnimation:40 picName:@"eat"];
[self creatPlay:@"p_eat.wav"];
}
//封装 执行动画方法
-(void)startAnimation:(int)count picName:(NSString*)picName
{
if(self.imageViewCat.isAnimating){
return;
}
//0.动态加载图片到NSArray中
NSMutableArray *arrayM = [[NSMutableArray alloc] init];
for (int i=0; i<count; i++) {
//根据图片名称加载图片
//通过imageName:这种方式加载图片,加载好的图片一致保存在内存中,不会释放,这样下次如果再次使用同样的图片的时候就不需要再重新加载,因为内存中已有。缺点:如果加载大量图片,那么这些图片会一直保存在内存中,导致应用占用内存过大,这就是缓存。
//UIImage *imaCat = [UIImage imageNamed:imgName];
//解决:换一种加载图片的方法,即:获取图片完整的路径
//获取图片的名称
NSString *imgName = [NSString stringWithFormat:@"cat_%@_%d.jpg",picName,i];
//获取图片的路径
NSString *path = [[NSBundle mainBundle] pathForResource:imgName ofType:nil];
//赋值给UIimage
UIImage *imgCat = [UIImage imageWithContentsOfFile:path];
[arrayM addObject:imgCat];
}
//1.设置ImageView的animationImages属性,包含执行动画的图片
self.imageViewCat.animationImages = arrayM;
//2.设置动画持续时间
self.imageViewCat.animationDuration = 3;
//3.设置动画重复播放次数
self.imageViewCat.animationRepeatCount = 1;
//4.开启动画
[self.imageViewCat startAnimating];
//5.当动画执行完毕之后,延迟一段时间,清空图片,达到请空内存的处理
[self.imageViewCat performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageViewCat.animationImages.count * 0.1];
}
//播放音乐
-(void) creatPlay:(NSString*) name
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"name" ofType:nil];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:nil];
[_player play];
}
@end