图像视图(UIImageView)用于显示图像。可以将图像视图加入到应用到应用程序中,并用于向用户呈现信息。UIImageView还可以创建简单的基于帧的动画,其中包括开始、停止和设置动画播放速度的控件。在使用Retina屏幕的设备中,图像视图可利用其高分辨率屏幕。让人兴奋的是,无需编写任何特殊代码,无需检查设备类型,而只需要将多幅图加入到项目中,图像将在正确的时间显示正确的图像。

UIImageView常用操作

UIImageView是放置图片的,当使用Interface Builder设计界面时,可以直接将空间拖进去并设置相关属性。

1.创建一个UIImageView

在ios应用中,有以下5种创建UIImageView对象的方法:

UIImageView *imageView1 = [[UIImageView alloc] init];
UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:<#(CGRect)#>];
UIImageView *imageView3 = [[UIImageView alloc] initWithImage:<#(nullable UIImage *)#>];
UIImageView *imageView4 = [[UIImageView alloc] initWithImage:<#(nullable UIImage *)#> highlightedImage:<#(nullable UIImage *)#>];
UIImageView *imageView5 = [[UIImageView alloc] initWithCoder:<#(nonnull NSCoder *)#>];

其中比较常用的是前3个,当使用第4个方法,highlighted属性值为YES时,显示的就是highlightedImage,一般情况显示第一个参数UIImage。

2.frame与bounds属性

上述第二个方法是在创建时就设定位置和大小。当以后想改变位置时,可以重新设定frame属性:

imageView.frame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);
在此需要注意UIImageView还有一个bounds属性,这个属性和frame有一点区别:frame属性用于设置位置和大小,而bounds属性只能设置其大小,x和y即便是设定了,也不会起到任何作用。bounds实现的是将UIImageView控件以原来的中心为中心进行缩放。

3.contentMode属性

这个属性用来设置图片的显示方式,如居中、居右、是否缩放等,有以下几个常量可供设定。

  • UIViewContentModeScaleToFill
  • UIViewContentModeScaleAspectFit
  • UIViewContentModeRedraw
  • UIViewContentModeCenter
  • UIViewContentModeTop
  • UIViewContentModeBottom
  • UIViewContentModeLeft
  • UIViewContentModeRight
  • UIViewContentModeTopLeft
  • UIViewContentModeTopRight
  • UIViewContentModeBottomLeft
  • UIViewContentModeBottomRight

在上述常量中,凡是没有带Scale的,当图片尺寸超过ImageView尺寸时,只有部分显示在ImageView中。UIViewContentModeScaleToFill会导致图片变形。UIViewContentModeScaleAspectFit会保证图片比例不变,而且全部显示在ImageView中,但ImageView会有部分空白。UIViewContentModeScaleAspectFill也会保证图片比例不变,是填充整个ImageView的,可能只有部分图片显示出来。

posted on 2018-10-08 17:08  广坤山货  阅读(125)  评论(0编辑  收藏  举报