最近,因业务需求需要根据不同的情况,设置不同的图片显示模式。于是,又Google了一把,虽然已经用过很多次了。所以,这里记录一下,加深一下自己的印象。
先看一下,官方 UIViewContentMode 的枚举类型:
typedef NS_ENUM(NSInteger, UIViewContentMode) {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent
UIViewContentModeScaleAspectFill, // contents scaled to fill with fixed aspect. some portion of content may be clipped.
UIViewContentModeRedraw, // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter, // contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
};
这里,记录一下几个自己经常用到的模式:
UIViewContentModeScaleToFill
在这种模式下,图片会按照 ImageView 的尺寸填充满;如果图片尺寸过大会被压缩,如果图片尺寸过小会被拉伸。图片很有可能会变形。
UIViewContentModeScaleAspectFit
这种模式,图片会等比例被拉伸或压缩。结果就是在一个方向上正好填充满时,另一个方向上可能会有空白。(图片比例和ImageView比例不相同)
UIViewContentModeScaleAspectFill
这种模式,图片会被等比例拉伸或压缩。结果就是在一个方向上刚好填充满时,另一个方向上可能已经超出了ImageView的大小,导致部分不会被显示出来。(图片比例和ImageView比例不相同)
UIViewContentModeCenter
这种模式,图片多大就是多大,会居中显示在ImageView中。
个人的一点小心得:
如果图片大小小于ImageView大小且要求居中显示,则用 UIViewContentModeCenter 比较好;但如果图片大小大于ImageView大小,建议不要用 UIViewContentModeCenter , 效果不是很好。
如果要求不要显示位于ImageView之外的图片部分(一般都是这样),则需要设置ImageView的 clipsToBounds 属性。
imageView.clipsToBounds = YES;