本文章的目的是阐明在UIImageView中如何正确的拉伸图片。
UIViewContentMode定义
typedef NS_ENUM(NSInteger, UIViewContentMode) {
//The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.
UIViewContentModeScaleToFill,
//The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
UIViewContentModeScaleAspectFit,
//The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.
UIViewContentModeScaleAspectFill, // contents scaled to fill with fixed aspect. some portion of content may be clipped.
//The option to redisplay the view when the bounds change by invoking the setNeedsDisplay method.
UIViewContentModeRedraw, // redraw on bounds change (calls -setNeedsDisplay)
UIViewContentModeCenter, // contents remain same size. positioned adjusted.
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
};
需要说明的是但凡包含Scale这个单词的值, 都会对原有的图片进行缩放。
这里我们着重说明前三个值
UIViewContentModeScaleToFill
铺满整个画布,图片会变形

UIViewContentModeScaleAspectFit 效果
图片不变形,画布会留有空白

UIViewContentModeScaleAspectFill 效果
图片不变形,铺满整个画布,图片会被裁剪

另外UIView中的contentMode对应的是CALayer中的contentGravity,那么二者之间的对应关系是什么呢
UIViewContentModeScaleToFill, => kCAGravityResizeAspectFill
UIViewContentModeScaleAspectFit, => kCAGravityResizeAspect
UIViewContentModeScaleAspectFill, => kCAGravityResize
UIViewContentModeRedraw, => ???
UIViewContentModeCenter, => kCAGravityCenter
UIViewContentModeTop, => kCAGravityTop
UIViewContentModeBottom, => kCAGravityBottom
UIViewContentModeLeft, => kCAGravityLeft
UIViewContentModeRight, => kCAGravityRight
UIViewContentModeTopLeft, => kCAGravityTopLeft
UIViewContentModeTopRight, => kCAGravityTopRight
UIViewContentModeBottomLeft, => kCAGravityBottomLeft
UIViewContentModeBottomRight, => kCAGravityBottomRight
};
网友评论