使用UIImageView播放动图

作者: NewBug | 来源:发表于2016-01-06 23:28 被阅读3788次

动图大家都会想到gif图片,但是在iOS端不能够播放gif格式图片怎么办呢。。。

其实苹果为开发者提供的控件足以让图片动起来,下面我选其中的一种使用UIImageView让图片动起来。。。


播放动图其实就是有许多张图片让他一张一张显示出来,在mac系统下打开gif格式图片就会看到,一张一张的图片,我们使用UIImageView播放图片其实就是让图片以动画的形式一张一张的播放出来;

使用UIImageView播放动图需要用到这些属性:

animationImages指向了NSArray说明这个就是存放所有需要播放的图片的数组;

animationDuration这个就是控制图片播放时间的属性;

animationRepeatCount这个是动画循环次数,默认是0,不循环;

这是需要用到的方法:

startAnimating方法是开始播放图片;

stopAnimating方法是结束播放图片;

isAnimating方法是判断图片是不是在播放;

下面直接上代码:

@property (nonatomic, strong)UIImageView *imageView;

首先创建存放图片的数组,并把图片存放到可变数组中:

NSMutableArray *tempArr = [NSMutableArray array];

for (int i = 0; i < count; i ++) {

//从bundle中获取的无缓存(图片所占用的内存会在一些特定操作后清除)

//behavior是定义的宏,是图片名字(例:head_01.jpg)

NSString *strImage = [NSString stringWithFormat:@"%@_%02d.jpg",behavior,i];

UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:strImage ofType:nil]];

[tempArr addObject:image];

}

//把存放图片的数组传给UIImageView的播放动画的数组

self.imageView.animationImages = tempArr;

//设置动画播放时间

self.imageView.animationDuration = 5.0f;

//设置动画连续播放次数

self.imageView.animationRepeatCount = 1;

//开始播放动图

[self.imageView startAnimating];

//此时完事,但是有一个致命性问题,你看一下内存使用情况,已经要爆了吧,下面就是内存优化问题了

//当动画播放结束时延迟一秒我们释放掉self.imageView.animationImages的image对象

[self.imageView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageView.animationDuration + 1.0f];

补充:如果使用bundle获取图片帧不要把图片拖到Assets.xcassets中获取,因为bundle获取的是当前程序可执行文件所在的目录下,而Assets.xcassets中得图片在编译时会被打包成Assets.car文件(想要获取Assets.xcassets中图片必须使用[UIImage imageNamed:]加载)。

相关文章

网友评论

  • 起个名字好难O0:animationRepeatCount 为0 是重复循环吧? 还有我设置1 的时候就不会显示动画. 然后有没有其他办法不重复动画, 抛弃定时器的概念.
  • 坤哥爱卿:好像不用这么麻烦吧,导入#import <UIImage+GIF.h>
    执行
    self.topIcon.image = [UIImage sd_animatedGIFNamed:@"icon_WLJC@2x.gif"];
    就OK了
    叉叉歪大魔王:傻逼 不是每个人都会用sd的
  • Stormstout:想问下怎么销毁内存,我是MRC模式,在返回时候要销毁对象的内存,用你上面的方法并没有成功,[self.imageView performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageView.animationDuration + 1.0f];
    或者可以获取self.imageView.animationImages的image对象么?

本文标题:使用UIImageView播放动图

本文链接:https://www.haomeiwen.com/subject/kctfkttx.html