iOS开发基础-序列帧动画之Tom猫

  新建一个Single View Application,向该工程中导入Tom猫的图片资源,本示例演示Tom猫喝牛奶的动作。图片的名字为 drink_00.jpg、drink_01.jpg、...、drink_80.jpg 。

  向 Main.storyboard 中添加 UIImageView ,将图片 drink_00.jpg 作为默认显示的画面。将该控件与 ViewController 类建立一个 IBOutlet 连接,属性名为: @property (weak, nonatomic) IBOutlet UIImageView *tomCat; 

  再添加大小为60*60的 UIButton 控件,将控件的名字设为 drink ,标题文字颜色为 Clear Color ,再将图片 milk.png 作为该按钮的背景图片。将该按钮控件与 ViewController 类建立一个 IBAction 动作连接,方法为 - (IBAction)buttonClicked:(id)sender; 。

  在 ViewController.m 中添加如下代码实现序列帧动画:

 1 //ViewController.m
 2 - (void)playAnimation:(int)count fileName:(NSString *)fileName {
 3     //创建可变数组存放序列帧图片
 4     NSMutableArray *images = [NSMutableArray array];
 5     for (int i = 0; i < count; i++) {
 6         // 图片名。%02d -- 当整数位数小于两位时,在前面自动补1个零
 7         NSString *name = [NSString stringWithFormat:@"%@_%02d.jpg", fileName, i];
 8         NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
 9         UIImage *img = [[UIImage alloc] initWithContentsOfFile:path];
10         [images addObject:img];
11     }
12     self.tomCat.animationImages = images;
13     self.tomCat.animationRepeatCount = 1;
14     self.tomCat.animationDuration = count * 0.1;
15     [self.tomCat startAnimating];
16 }
17 
18 - (IBAction)buttonClicked:(id)sender {
19     //如果正在播放动画则直接返回
20     if (self.tomCat.isAnimating) {
21         return;
22     }
23     int count = 81;     //图片数量
24     NSString *title = @"drink";
25     //播放动画
26     [self playAnimation:count fileName:title];
27 }

效果图如下:

参考博客:iOS开发UI篇—iOS开发中三种简单的动画设置

实例代码:http://pan.baidu.com/s/1pKgR56V

posted @ 2016-01-29 20:25  pestle  阅读(1308)  评论(0编辑  收藏  举报