开发中经常遇到给图片设置图片,图片的比例和UIButton 的宽高比例相同时是没什么问题的,图片不会因为被拉伸或者缩放而出现失真。但是当图片的比例和 Button 的尺寸比例不一样时,这两种方式设置图片的效果就不一样了。
有两种方式给它设置一张图片:setBackgroundImage:forState: 和 setImage:forState:
下面记录一下遇到的各种情况
button设置如下
let button = UIButton(type: .custom)
self.view.addSubview(button)
button.frame = CGRect(x: 50, y: 200, width: 300, height: 200);
button.backgroundColor = UIColor.lightGray
button.layer.borderColor = UIColor.red.cgColor
button.layer.borderWidth = 1
小图的size为 200 × 119 pixels
大图的size为 1142 × 640 pixels
-
setBackgroundImage
小图
button.setBackgroundImage(UIImage(named: "small"), for: .normal)
不设置显示模式,显示如下图
smallbackground.png
图片被拉伸到和button的size一样大小
大图
button.setBackgroundImage(UIImage(named: "big"), for: .normal)
不设置显示模式,显示如下图

图片被压缩到和button的size一样大小显示
设置contentMode,大图和小图均无效
button.contentMode = .scaleAspectFit
button.contentMode = .scaleAspectFill
button.contentMode = .bottom
button.imageView?.contentMode = .scaleAspectFit
button.imageView?.contentMode = .scaleAspectFill
button.imageView?.contentMode = .bottom
-
setImage
小图
显示如下
smallimage.png
button.setImage(UIImage(named: "small"), for: .normal)
// 小图以自己的size显示在button中
// 以下contentMode设置均无效
button.contentMode = .scaleAspectFit
button.contentMode = .scaleAspectFill
button.contentMode = .bottom
button.imageView?.contentMode = .scaleToFill
button.imageView?.contentMode = .scaleAspectFit
button.imageView?.contentMode = .scaleAspectFill
button.imageView?.contentMode = .bottom
如果想要设置小图填充满button,设置contentHorizontalAlignment和contentVerticalAlignment的填充模式,可以达到第一张图片的效果
代码如下
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
大图
button.setImage(UIImage(named: "big"), for: .normal)
默认大图完全填充成button的size显示,如下图

设置contentMode:scaleToFill
button.imageView?.contentMode = .scaleToFill
显示如上图
设置contentMode:scaleAspectFit
button.imageView?.contentMode = .scaleAspectFit
图片比例不变,大小拉伸适合button的size 如下图

设置contentMode:top
button.imageView?.contentMode = .top
图片比例和大小不变,以图片的左上角为原点显示在button上 如下图

其他模式就不一一列举了。
网友评论