iOS - UIImageView
前言
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIImageView : UIView
@available(iOS 2.0, *) public class UIImageView : UIView
需要注意的是,Apple 对 png 格式图片支持最为良好的,对于其他格式支持相对较弱,当图片是 png 格式,那么图片名的后缀 .png 可以不写,但是如果图像只有 @2x 图片,没有一倍图像,则不能忽略 .png,在 iPhone4 以后,苹果采用视网膜屏幕,所以就有了 2 倍像素图像,随着发展现在有了 @3x 图,如果你现在还在用 Xcode5.1 写程序,在适配 iPhone6 以及 6+ 会自动放大即可,但是在 Xcode6 上就需要考虑适配问题,不会自动适配了。
如果不是 png 格式,请务必要加入后缀名,否则可能无法显示。比如目前无法直接加载 gif 图。
1、UIImageView 的创建
Objective-C
先设置 frame 后添加 image
// 创建一个图片视图,只有图片 image 是显示不出来的,需要 image 放到 imageView 上才能显示出来
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
imageView.image = [UIImage imageNamed:@"1"];
[self.view addSubview:imageView];
先添加 image 后设置 frame
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"13"]];
// 可以不设置 frame,不设置时 imageView 的大小 与 image 的大小相同
imageView.frame = self.view.bounds;
[self.view addSubview:imageView];
Swift
先设置 frame 后添加 image
// 创建一个图片视图,只有图片 image 是显示不出来的,需要 image 放到 imageView 上才能显示出来
let imageView:UIImageView = UIImageView(frame: self.view.bounds)
imageView.image = UIImage(named: "1")
self.view.addSubview(imageView)
先添加 image 后设置 frame
let imageView:UIImageView = UIImageView(image: UIImage(named: "13"))
// 可以不设置 frame,不设置时 imageView 的大小 与 image 的大小相同
imageView.frame = self.view.bounds
self.view.addSubview(imageView)
2、UIImageView 的设置
Objective-C
// 设置 frame
/*
imageView.image.size.width, imageView.image.size.height 可获取 imageView image 中图片的尺寸
*/
imageView.frame = CGRectMake(10, 30, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.height - 40);
// 设置图片填充方式
/*
当图片小于 imageView 的大小时,处理图片的显示方式
// 缩放图片,使图片充满容器。图片未必保持长宽比例协调,有可能会拉伸至变形。默认
UIViewContentModeScaleToFill,
// 在保持长宽比的前提下,缩放图片,使得图片在容器内完整显示出来
UIViewContentModeScaleAspectFit,
// 在保持长宽比的前提下,缩放图片,使图片充满容器
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
*/
imageView.contentMode = UIViewContentModeScaleToFill;
// 设置透明度
imageView.alpha = 0.5;
// 设置 image
/*
图片名称为 nil 时,控制台会打印输出 CUICatalog: Invalid asset name supplied: (null)
*/
// 正常状态时的图片
imageView.image = [UIImage imageNamed:@"18"];
// 高亮状态时的图片
imageView.highlightedImage = [UIImage imageNamed:@"17"];
// 设置是否隐藏
imageView.hidden = YES;
// 设置 imageView 的交互属性
/*
UIImageView 的交互属性默认是关闭的
*/
imageView.userInteractionEnabled = YES;
// 为图片添加单击事件
/*
一定要先将 userInteractionEnabled 置为 YES,这样才能响应单击事件
*/
[imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapImageView:)]];
Swift
// 设置 frame
/*
imageView.image.size.width, imageView.image.size.height 可获取 imageView image 中图片的尺寸
*/
imageView.frame = CGRectMake(10, 30, UIScreen.mainScreen().bounds.size.width - 20, UIScreen