contentMode是UIView的屬性(如下圖),這個(gè)屬性的值決定了,當(dāng)視圖的幾何形狀變化時(shí)如何復(fù)用它的內(nèi)容。當(dāng)視圖第一次展示前,它會(huì)將自己的內(nèi)容渲染成一張底層的bitmap. 然后視圖的幾何變化都不會(huì)使bitmap重新生成。而視圖contentMode屬性的值決定了bitmap是否縮放、位置在哪兒(固定在左邊、右邊、上面、下面、居中)。默認(rèn)情況下,contentMode的值是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,
};
contentMode在以下兩種情況下會(huì)起作用:
1.視圖frame或bounds的高寬發(fā)生變化
2.賦給 view的transform屬性的值帶有scale
UIViewContentModeScaleToFill:改變內(nèi)容的高寬比例,縮放內(nèi)容,UIView中完整顯示內(nèi)容,填滿UIView
UIViewContentModeScaleAspectFit:保持內(nèi)容的高寬比,縮放內(nèi)容,完整顯示內(nèi)容,最大化填充UIview,沒(méi)填充上的區(qū)域透明
UIViewContentModeScaleAspectFill:保持內(nèi)容高寬比,縮放內(nèi)容,超出視圖的部分內(nèi)容會(huì)被裁減,填充UIView,需要把View的 clipsToBounds 設(shè)置為YES;
UIViewContentModeRedraw:當(dāng)View的bounds改變,系統(tǒng)會(huì)調(diào)用setNeedsDisplay,重新繪制視圖
UIViewContentModeCenter:不縮放,內(nèi)容在視圖中間
效果圖如下:
