- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 500)];
imageView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:imageView];
imageView.center = self.view.center;
imageView.image = [UIImage imageNamed:@"1.png"];
//填充图像位置 因为imageView继承自UIView 所以UIView属性可以被继承,imageView经常用到下面这个属性
//UIViewContentModeBottom 最下面居中
//UIViewContentModeBottomLeft 最下面靠左
//UIViewContentModeBottomRight 最下面靠右
//UIViewContentModeCenter 居中
//UIViewContentModeLeft 居中靠左
//UIViewContentModeRight 居中靠右
//UIViewContentModeRedraw 铺满imageView
//UIViewContentModeScaleAspectFill 根据imageView最大边长等比例放大,imageView随之一样大
//UIViewContentModeScaleAspectFit image根据imageView最小边长等比例缩放,imageView不变
//UIViewContentModeScaleToFill 填满imageView
//UIViewContentModeTop 最上面居中
//UIViewContentModeTopLeft 最上面居中
//UIViewContentModeTopRight 最上面居中
imageView.contentMode = UIViewContentModeTop;
//打开imageView的用户响应,默认为NO。若要为imageView添加响应事件需置为YES
// imageView.userInteractionEnabled = YES;
}
<pre name="code" class="objc">// UIImageView 是用来展示图片的,但是也可以播放动态图片
// mac系统的动态图片存在桌面上,打开后显示为xxx.tiff格式图片,把这些图片导入到工程中,存在imageView里,代码如下:
//(1)准备素材,存在数组中
NSMutableArray *arr = [NSMutableArray array];
for (int i = 1; i < 23; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"run%d.tiff",i]];
[arr addObject:image];
}
//(3)指定ImageView的素材库 为上面的数组
self.imageView.animationImages = arr;
//(4)设置循环时间
self.imageView.animationDuration = 1.0f;
//(5)循环次数,0 为无限循环
self.imageView.animationRepeatCount = 0;
//(6)开始 动画
[self.imageView startAnimating];
//开始执行动画
[self.imageview startAnimating];
//停止动画
[imageView stopAnimating];
//动画播放状态
BOOL flag = [imageView isAnimating];
关于UIImageView内存问题,用动画为例子。代码与上面的相同,注释不一样
//清理图片所占内存
//经常用的图片放在Images.xcasssets中的图片,不能用imageWithContentsOfFile方法
//不经常用的图片直接托拖入工程即可
NSMutableArray *imgArr = [NSMutableArray array];
for (int i = 1; i < 14; i++) {
//系统管理图片,内存不释放
NSString *str = [NSString stringWithFormat:@"%d.png",i];
//imageNamed 不能释放,数组置为空也不行,图片在缓存中
//UIImage *image = [UIImage imageNamed:str];
//自己从文件获取,数组改变时上一组图片释放,可手动释放,把数组置为空就行
//获取图片路径
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:nil];
UIImage *image = [UIImage imageWithContentsOfFile:path];
[imgArr addObject:image];
}
//下面代码与上面的动画一样,可不看,若想试验内存问题 粘贴复制即可。
self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
self.imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:self.imageView];
self.imageView.center = self.view.center;
self.imageView.animationImages = imgArr;
self.imageView.animationDuration = 1;
self.imageView.animationRepeatCount = 10;
[self.imageView startAnimating];
//动画播放完毕后清理
//清理image内存 下面的方法是一种消息处理方法,具体以后在分析
[self performSelector:@selector(clearImg) withObject:nil afterDelay:1];
//清理数组
-(void)clearImg{
self.imageView.animationImages = nil;
}