
7.3 图片控件UIImageView
7.3.1 基本使用
UIImageView是用来显示图片的UI控件,在使用过程中需要重点区分UIImageView以及UIImage的区别,另外,还需要重点掌握UIImageView的创建以及相关样式设置的操作方法。
1.UIImageView与UIImage的区别
UIImageView与UIImage对于初学者来讲比较容易混淆,因此在学习UIImageView之前,首先需要了解UIImageView与UIImage的联系和区别。
- UIImageView:这是UI控件,继承自UIView,是用来显示图片的控件,UIImageView中有一个UIImage类型的属性——image,用来存放需要显示的图片。
- UIImage:可以理解为是图片文件,文件是不能显示的,文件相当于保存在磁盘上的一堆二进制编码。UIImage的父类是NSObject。创建UIImage对象可以使用imageNamed:以及imageWithContentsOfFile:方法,区别在于需要传入的图片文件的路径不同。

2.UIImageView对象的创建
UIImageView对象的创建可以使用代码以及XIB的方式创建。当使用代码方式创建时,可以使用如下方法:

运行结果如图7-28所示。

图7-28 运行结果
当使用XIB的方式创建UIImageView时,可以在Storyboard中添加UIImageView控件,并对其image属性进行设置,如图7-29所示。

图7-29 XIB方式创建UIImageView
7.3.2 常用操作
当创建完成一个UIImageView对象后,通常情况下会对其样式进行一些定制,例如,裁剪UIImageView对象的边角,添加边框,添加手势等。
1.设置圆角/圆形头像
默认情况下,UIImageView是一个矩形,其边角是没有圆滑过渡的。在实际的开发过程中,经常需要把图片的边角设置为圆角,此时可以通过修改UIImageView的layer属性实现,如图7-30所示。

图7-30 圆角效果

通过上面的方法,当设置cornerRadius的值为UIImageView宽度的一半时,最终展示的就是一个圆形的图片,如图7-31所示。

图7-31 圆形图片
2.设置边框
UIImageView对象创建后,默认情况下是没有边框的,可以通过修改layer的borderWidth以及borderColor来设置UIImageView的边框属性。

运行结果如图7-32所示。

图7-32 设置边框
3.添加手势点击事件
默认情况下,UIImageView对象是不能够响应用户交互的,这是因为在UIImageView类中其userInteractionEnabled属性的默认取值为NO。这里可以修改该属性的值,并且为该UIImageView对象添加手势后,即可响应用户交互。

下面的示例代码中为imageView对象添加了一个点击手势。

7.3.3 帧动画功能
UIImageView可以支持帧动画的播放,即按照顺序播放一组图片,如果播放足够快,会有动画效果,原理同早期的胶片电影播放一致。在若干年前流行的“会说话的TOM猫”,就是利用UIImageView的帧动画播放功能实现。
1.UIImageView动画播放相关属性与方法
在UIImageView类中定义了如下与帧动画播放相关的属性和方法,通过设置这些属性和方法就可以实现帧动画的播放。
- 图片存放的数组。把所有需要播放的图片有序地放到该数组中。

- 动画播放的时长,默认取值为:animationImages中图片的数量*1/30。

- 动画播放的次数。

- 动画播放与停止。

2.自动清除
由于animationImages数组会在内存中保存大量的图片,且动画播放完毕后不会自动销毁,所以会一直占用较大的内存,因此,动画播放完毕后需要自动清除该属性中保存的图片。通常的操作方式是在动画播放完成后,把该数组指向nil。
