本项目是取自传智播客的教学项目,加入笔者的修改和润饰。
1. 项目名称:汤姆猫
2. 项目截图展示
3. 项目功能
- 点击特定按钮,播放动画
4. 项目代码
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *tom;
@end
@implementation ViewController
//参数:图片名字和图片个数
- (void) tomAnimationWithName:(NSString *)name andCount:(int)count
{
//如果正在动画,直接退出
if (self.tom.isAnimating==YES)return;
//指定动画图片等数组
NSMutableArray *arrayM = [NSMutableArray array];
//添加动画播放的图片
for (int i=0; i <count ; i ++) {
//需要知道第i个图片等名称来获取该图片的全路径
NSString *imageName =[NSString stringWithFormat:@"%@_%02d.jpg",name,i];
//需要图片的全路径来提取图片
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
//取出第i个图片
UIImage *image = [UIImage imageWithContentsOfFile:path];
//在存放图片的数组中存放第i个图片
[arrayM addObject:image];
}
//设置存放播放动画所需的图片的数组
self.tom.animationImages = arrayM; //animationImages是UIImageView的属性
//动画只重复一次
self.tom.animationRepeatCount = 1;
//动画持续时长
self.tom.animationDuration = self.tom.animationImages.count*0.075;
//动画开始
[self.tom startAnimating];
//动画结束之后,清理动画数组
[self.tom performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.tom.animationDuration ];
}
//将按钮的tag设置为播放按钮之后播放动画所需的图片个数
//将按钮的名字设置为能提取播放动画所需图片的名字
- (IBAction)tomAction: (UIButton*)sender
{
//currentTitle可以取出按钮当前的标题文字
[self tomAnimationWithName:sender.currentTitle andCount:sender.tag];
}
//另一种播放动画的方法:针对每个按钮,单独实现方法
/*
- (IBAction)eatBird {
[self tomAnimationWithName:@"eat" andCount:40];
}
*/
@end
5. 本项目必须掌握的代码段
- 设置播放动画的数组
NSMutableArray *arrayM = [NSMutableArray array];
for (int i=0; i <count ; i ++) {
//提取第i个图像的名称 angry_00.jpg 00: %02d
NSString *imageName =[NSString stringWithFormat:@"%@_%02d.jpg",name,i];
//根据名称提取第i个图片的全路径
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
//根据路径取出第i个图片
UIImage *image = [UIImage imageWithContentsOfFile:path];
//在存放图片等数组中存放第i个图片
[arrayM addObject:image];
}
- 动画结束后,清理动画数组
[self.tom performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.tom.animationDuration ];
6. 笔记
6.1 内存管理相关
本项目稍微接触了一下内存管理的内容:在播放完动画之后,要及时清理动画的数组
6.2 UIImageView和UIButton的相同点和不同点
使用场合
- UIImageView: 如果仅仅是显示图片,不需要监听图片的点击
- UIButton: 既要显示图片,又要监听图片的点击
相同点:能显示图片
不同点:
- UIButton能处理点击事件, UIImageView不能处理点击事件
- UIButton既能显示图片, 又能显示文字
- UIButton能同时显示两张图片
- UIButton继承自UIControl, 因此默认就能处理事件
- UIImageView继承自UIView, 因此默认就不能处理事件