淺談UIView的contentMode屬性

Content Modes###

每一個(gè)view都有一個(gè)contentMode屬性。這個(gè)屬性用來(lái)控制view如何重用界面的內(nèi)容以響應(yīng)界面的幾何變化,或者是將整個(gè)內(nèi)容完全重用。
當(dāng)一個(gè)view第一次被展示的時(shí)候,它會(huì)將自己的內(nèi)容渲染為一張位圖。之后,改變view的幾何尺寸不會(huì)總是導(dǎo)致這個(gè)位圖重繪。相反的,contentMode屬性決定了這個(gè)位圖會(huì)如何顯示,是進(jìn)行縮放以適應(yīng)新的尺寸,或者只是簡(jiǎn)單的與某一個(gè)邊緣或者頂點(diǎn)對(duì)齊。

當(dāng)做以下操作都會(huì)使得contentMode屬性生效:

  • 修改view的frame或者bounds屬性的width或者h(yuǎn)eight
  • 給view的transform賦一個(gè)具有縮放動(dòng)作的值

系統(tǒng)提供了如下的屬性

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的默認(rèn)屬性是UIViewContentModeScaleToFill,這個(gè)屬性使得contents進(jìn)行縮放以適應(yīng)新的frame。
下圖展示了不同的屬性所產(chǎn)生的效果:

scale_aspect.jpg

由圖中看到UIViewContentModeScaleToFill屬性會(huì)導(dǎo)致形變。而
UIViewContentModeScaleAspectFill導(dǎo)致內(nèi)容不能完全展示.

content modes是界面重用內(nèi)容的好方法,當(dāng)然你也可以設(shè)置UIViewContentModeRedraw,使得你的自定義界面在尺寸變化時(shí)強(qiáng)制重繪。當(dāng)設(shè)置contentModel屬性為UIViewContentModeRedraw后,在view尺寸變化時(shí),系統(tǒng)會(huì)強(qiáng)制調(diào)用drawRect:方法。一般來(lái)說(shuō),你應(yīng)該盡可能的避免使用這個(gè)值,并且確保沒(méi)有給系統(tǒng)標(biāo)準(zhǔn)view設(shè)定這個(gè)值。

參考###

View and Window Architecture

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容