UIView contentMode属性详解

1、官方文档说明
  • contentMode

    A flag used to determine how a view lays out its content when its bounds change.(当一个view的bounds变化的时候用于决定其内容怎么变化。)

  • Declaration

    @property(nonatomic) UIViewContentMode contentMode;

  • Discussion

    The content mode specifies how the cached bitmap of the view’s layer is adjusted when the view’s bounds change. This property is often used to implement resizable controls. Instead of redrawing the contents of the view every time, you can use this property to specify that you want to scale the contents (either with or without distortion) or pin them to a particular spot on the view.(这一属性通常用于实现可调整大小的控制,通常与contentStretch属性一起使用。通过使用这一属性来决定你扩充的模式,从而避免了之前每次都要重新对view的内容进行重画。)

  • note:

    You can always force the contents of a view to be redrawn by calling the setNeedsDisplay or setNeedsDisplayInRect: method.(你可以使用 setNeedsDisplay或者setNeedsDisplayInRect:方法来强制对一个view进行重绘。)

2、UIViewContentMode属性值
  • UIViewContentMode是一个枚举类型,默认值是 UIViewContentModeScaleToFill
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,
};
  • UIViewContentModeScale
    • 前三个枚举值包含Scale,Scale在英文中有比例,缩放的意思。所以前三个以UIViewContentModeScale开头的属性,表示图片会被进行缩放。
    • UIViewContentModeScaleToFill The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary.(这个选项通过缩放其中内容(往往是图片)的大小来符合View自己的大小,如果需要的话会改变内容的长宽比例,缩放内容,UIView中完整显示内容)简单来说就是:扭曲、填满
    • UIViewContentModeScaleAspectFit 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.(这个选项通过按比例缩放内容(往往是图片)的大小来符合View的大小,与此同时,保持内容的长宽比例不变。而整个View没有被覆盖到的地方都是透明的(也就说会显示View的backgroundColor))简单来说就是:不变形、尽可能填满、留空
    • UIViewContentModeScaleAspectFill 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.(这个选项通过按比例缩放内容(往往是图片)的大小来填充整个View,与此同时,保持内容的长宽比例不变,超出视图的部分内容会被裁减。)简单来说就是:不变形、完全填满,需要把View的 clipsToBounds 设置为YES;
  • UIViewContentMode
    • 对应的,其他没有Scale的属性,都是指图片会保持原来的大小。以UIViewContentModeLeft为例,就是图片左对齐显示,能显示多少就显示多少。
3、实际显示效果展示
  • 原图大小为272x92,下面的每个正方形大小为100x100
    image

    实际效果展示代码地址
    参考1
    参考2
    官方文档

你可能感兴趣的:(UIView contentMode属性详解)