iOS开发之Tom猫

知识点:

imageNamed:系统推荐使用,但是图像实例化后的释放由系统负责,如果要自己释放图片,不能使用imageNamed。经常使用的资源用这个。

UIImage *image = [UIImage imageNamed:imageName];

不经常使用的,很大的资源用这个:

NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:path];

git地址:https://git.oschina.net/taylordavid/Tom.git

部分代码展示:

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *tom;

@end

@implementation ViewController

/*
 重构-抽取代码
 1/将重复代码复制到新的方法中
 2/根据需要调整参数
 */
- (void)tomAnimation:(NSString *)name count:(NSInteger)count {
    // 如果动画中,不执行
    if ([self.tom isAnimating]) {
        return ;
    }
    // 动画图片的数组
    NSMutableArray *arrayM = [NSMutableArray array];
    
    // 添加动画播放的图片
    for (int i = 0; i < count; ++i) {
        // 图像名称
        NSString *imageName = [NSString stringWithFormat:@"%@_%02d.jpg", name, i]; // 确保格式eat_01.jpg
        NSLog(@"%@", imageName);
        // UIImage *image = [UIImage imageNamed:imageName]; // 会内存叠加
        NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        
        [arrayM addObject:image];
    }
    // 设置动画数组
    self.tom.animationImages = arrayM;
    // 重复一次
    self.tom.animationRepeatCount = 1;
    // 动画时长
    self.tom.animationDuration = self.tom.animationImages.count * 0.075;
    // 开始动画
    [self.tom startAnimating];
    
    // 动画结束之后,清理动画数组
    // 一段时间之后执行clearup方法
    [self performSelector:@selector(clearup) withObject:nil afterDelay:self.tom.animationDuration];
}

- (void)clearup {
    // self.tom.animationImages = nil;
    [self.tom setAnimationImages:nil];
}

// 晕倒
- (IBAction)knockout:(id)sender {
    [self tomAnimation:@"knockout" count:81];
}

// 吃鸟
- (IBAction)eatBird:(id)sender {
    [self tomAnimation:@"eat" count:40];
}

// 打镲
- (IBAction)cymbal:(id)sender {
    [self tomAnimation:@"cymbal" count:13];
}

// 放屁
- (IBAction)fart:(id)sender {
    [self tomAnimation:@"fart" count:28];
}

// 抓玻璃
- (IBAction)scratch:(id)sender {
    [self tomAnimation:@"scratch" count:56];
}

// 扔蛋糕
- (IBAction)pie:(id)sender {
    [self tomAnimation:@"pie" count:24];
}

// 喝牛奶
- (IBAction)drink:(id)sender {
    [self tomAnimation:@"drink" count:81];
}

// 左脚
- (IBAction)footLeft:(id)sender {
    [self tomAnimation:@"footLeft" count:30];
}

// 右脚
- (IBAction)footRight:(id)sender {
    [self tomAnimation:@"footRight" count:30];
}

// 肚子
- (IBAction)stomach:(id)sender {
    [self tomAnimation:@"stomach" count:34];
}

// 胸
- (IBAction)angry:(id)sender {
    [self tomAnimation:@"angry" count:26];
}

@end

效果展示:

iOS开发之Tom猫_第1张图片

你可能感兴趣的:(ios,TOM猫)