UIImageView介绍
UIImageView 是一个用来在界面上显示单张图片或者图片序列的对象。
UIImageView 可以让你能够有效地使用 UIImage 对象来显示任何图像。例如,可以使用 Imageview 类来显示许多标准图像文件,例如 JPEG 和 PNG 文件。
UIImageView的创建
UIImageView 除了继承于 UIView 的 init 方法以外,还提供了以下两种 init 方法:
- (instancetype)initWithImage:(nullable UIImage *)image;
- (instancetype)initWithImage:(nullable UIImage *)image highlightedImage:(nullable UIImage *)highlightedImage;
一般使用的的是第一种方法,需要的参数是一个 UIImage 对象,也就是需要传入一个需要显示的图片对象。
以下是比较常用的创建 UIImage 的对象的所用的方法:
+ (UIImage *)imageNamed:(NSString *)name;
+ (UIImage *)imageWithContentsOfFile:(NSString *)path;
两种方法需要对应不同的情况使用,第一种方法适用于加载需要重用的图片,第二种方法适用于加载只使用一次的图片,并且无论使用哪种方法,都需要在不使用的时候将内存释放。 代码示例:
UIImage *img = [UIImage imageNamed:@"MyImage"];
UIImageView *imageView = [UIImageView initWithImage:img];
UIImageView的图片序列播放
UIImageView 可以通过一个图片数组来播放图片序列。
想要播放图片序列,需要完成以下几个步骤。
- 将图片数组赋值给
UIImageView对象的animationImages属性。 - 设置
UIImageView对象播放图片序列的animationDuration(动画时长)和animationRepeatCount(动画重复次数) - 调用
startAnimating对象方法开始动画。
另外还有一些使用方法:
- 想让动画停止时可以调用
stopAnimating对象方法停止动画。 - 对象的
animating参数返回一个布尔值表示是否正在播放动画。
代码示例:
NSMutableArray *arr = [NSMutableArray new];
for (int i = 0; i<10; i++) {
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
[arr addObject:img];
}
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 200, 300)];
imgView.animationImages = arr;
[self.view addSubview:imgView];
[imgView startAnimating];
UIImageView常用属性
contentMode : UIViewContentMode类型,UIImageView 的 contentMode 属性继承自 UIView,用来控制图片的拉伸效果。
UIViewContentMode是一个枚举类型,以下是其包含的内容:
- UIViewContentModeScaleToFill :拉伸至充满视图
- UIViewContentModeScaleAspectFit : 按原比例拉伸至合适
- UIViewContentModeScaleAspectFill : 按原比例拉伸至填充视图
- UIViewContentModeRedraw : 重绘视图边界
- UIViewContentModeCenter :视图中心对齐
- UIViewContentModeTop : 视图顶部对齐
- UIViewContentModeBottom : 视图底部对齐
- UIViewContentModeLeft : 视图左侧对齐
- UIViewContentModeRight : 视图右侧对齐
- UIViewContentModeTopLeft : 视图左上角对齐
- UIViewContentModeTopRight : 视图右上角对齐
- UIViewContentModeBottomLeft : 视图左下角对齐
- UIViewContentModeBottomRight : 视图右下角对齐
需要根据需求选择合适的效果。