iOS开发中UIImageView控件的常用操作整理

2020-01-14 18:41:28于丽
易采站长站为您分析iOS开发中UIImageView控件的常用操作整理,代码基于传统的Objective-C,需要的朋友可以参考下  

UIImageView,顾名思义,是用来放置图片的。使用Interface Builder设计界面时,当然可以直接将控件拖进去并设置相关属性,这就不说了,这里讲的是用代码。

1、创建一个UIImageView:

创建一个UIImageView对象有五种方法:

复制代码
UIImageView *imageView1 = [[UIImageView alloc] init]; UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:(CGRect)]; UIImageView *imageView3 = [[UIImageView alloc] initWithImage:(UIImage *)]; UIImageView *imageView4 = [[UIImageView alloc] initWithImage:(UIImage *) highlightedImage:(UIImage *)]; UIImageView *imageView5 = [[UIImageView alloc] initWithCoder:(NSCoder *)];
比较常用的是前边三个。至于第四个,当这个ImageView的highlighted属性是YES时,显示的就是参数highlightedImage,一般情况下显示的是第一个参数UIImage。

 

2、frame与bounds属性:

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

复制代码
imageView.frame = CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat heigth);
注意到UIImageView还有一个bounds属性
复制代码
imageView.bounds = CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat heigth);
那么这个属性跟frame有什么区别呢?

 

我的理解是,frame设置其位置和大小,而bounds只能设置其大小,其参数中的x、y不起作用即便是之前没有设定frame属性,控件最终的位置也不是bounds所设定的参数。bounds实现的是将UIImageView控件以原来的中心为中心进行缩放。例如有如下代码:

复制代码
imageView.frame = CGRectMake(0, 0, 320, 460); imageView.bounds = CGRectMake(100, 100, 160, 230);
执行之后,这个imageView的位置和大小是(80, 115, 160, 230)。

 

3、contentMode属性:

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

复制代码
UIViewContentModeScaleToFill UIViewContentModeScaleAspectFit UIViewContentModeScaleAspectFill UIViewContentModeRedraw UIViewContentModeCenter UIViewContentModeTop UIViewContentModeBottom UIViewContentModeLeft UIViewContentModeRight UIViewContentModeTopLeft UIViewContentModeTopRight UIViewContentModeBottomLeft UIViewContentModeBottomRight