UIImageView及相关图片(UIImage)处理问题
2016-08-07 本文已影响52人
Kevin_wzx
1.简单认识
UIImageView对象提供了一个基于视图的容器来展示一张或者一系列图像,同时也支持以动画的方式来呈现一组图像(可以指定播放间隔和频率)。简单的说,UIImageView就是UIImage对象的承载者,当需要将UIImage呈现在UIView上时就需要UIImageView。二者的关系就像UILabel和NSString之间的关系。
2.属性~方法
UIImageView的常用属性和方法:
- contentMode属性:图片的填充模式。(继承自UIView)
- clipsToBounds属性:修剪超出边界的部分。(继承自UIView)
- animationImages属性:装在用于动画的图像的数组。
- animationDuration属性:动画播放的持续时间。
- animationRepeatCount属性:动画的重复次数,0表示循环播放。
- -startAnimating方法:开始播放动画。
- -stopAnimating方法:停止播放动画。
- -isAnimating方法:返回BOOL值表示动画是否正在播放中。
2.1 三种contentMode属性
屏幕快照 2016-08-31 下午2.30.23.png3.用UIImageView来实现一个动画的demo如下:
#import "ViewController.h"
@interface ViewController () {
NSTimer *timer;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 用一个数组来装构成动画的所有图片
NSMutableArray *imageArray = [NSMutableArray array];
for (int i = 0; i < 6; i++) {
[imageArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"runner%d.jpg", i]]];
}
// 创建UIImageView对象并指定相关的动画图片
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 150, 75, 100)];
imageView.animationImages = [imageArray copy];
// 设置图片切换的时间间隔
imageView.animationDuration = 0.5;
imageView.tag = 101;
// imageView.animationRepeatCount = 10;
// 开始动画
[imageView startAnimating];
[self.view addSubview:imageView];
// 启动一个计时器让UIImageView向右移动
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(runAhead) userInfo:nil repeats:YES];
}
// 修改UIImageView的x坐标使其向右移动并在到达边界时返回
- (void) runAhead {
UIImageView *currentView = (id)[self.view viewWithTag:101];
CGRect rect = currentView.frame;
rect.origin.x += 1;
if(rect.origin.x > self.view.bounds.size.width) {
rect.origin.x = -75;
}
currentView.frame = rect;
}
@end
效果大致如下:
屏幕快照 2016-08-07 上午1.57.33.png 屏幕快照 2016-08-07 上午1.57.40.png4.UIImage简介
屏幕快照 2017-04-21 下午3.04.07.png // 此种方式会对加载的图片进行单例处理,不适合动态加载大量图片,因为单例对象会一直存在于内存中
UIImage *image1 = [UIImage imageNamed:@"abc"];
NSString * strPath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"png"];
// 此方式适合本地动态加载大量图片,而且即使加载很大的图片也不会使程序崩溃,前一种方式加载大图片可能会出现问题
UIImage *image2 = [UIImage imageWithContentsOfFile:strPath];
// 通过制定URL得到的数据创建图片对象
UIImage *image3 =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://www.baidu.com/img/bdlogo.png"]]];
屏幕快照 2017-04-21 下午3.04.56.png
5.image的几种加载方式的选择(性能优化)
两种取“本地图片”的方式的区别
1.imageName:这种方法加载图片相当于做了一次单例的处理,适合于加载小图标小图片等基本素材;其生命周期不会结束(单例相当于全局变量);内存不会释放?
2.通过文件方式获取(适合于加载大量图片或动态图片);内存维持的比较好
imageWithContentsOfFile: