ios開發(fā)shouldRasterize光柵化--離屏渲染

shouldRasterize(光柵化)是比較特別的一種離屏渲染:
光柵化概念:將圖轉(zhuǎn)化為一個個柵格組成的圖象。
光柵化特點(diǎn):每個元素對應(yīng)幀緩沖區(qū)中的一像素。

/* When true, the layer is rendered as a bitmap in its local coordinate
 * space ("rasterized"), then the bitmap is composited into the
 * destination (with the minificationFilter and magnificationFilter
 * properties of the layer applied if the bitmap needs scaling).
 * Rasterization occurs after the layer's filters and shadow effects
 * are applied, but before the opacity modulation. As an implementation
 * detail the rendering engine may attempt to cache and reuse the
 * bitmap from one frame to the next. (Whether it does or not will have
 * no affect on the rendered output.)
 *
 * When false the layer is composited directly into the destination
 * whenever possible (however, certain features of the compositing
 * model may force rasterization, e.g. adding filters).
 *
 * Defaults to NO. Animatable. */

@property BOOL shouldRasterize;

/* The scale at which the layer will be rasterized (when the
 * shouldRasterize property has been set to YES) relative to the
 * coordinate space of the layer. Defaults to one. Animatable. */

@property CGFloat rasterizationScale;

光柵化有什么好處?

當(dāng)shouldRasterize設(shè)成true時,layer被渲染成一個bitmap位圖,并緩存起來,等下次使用時不會再重新去渲染了。實現(xiàn)圓角本身就是在做顏色混合(blending),如果每次頁面出來時都blending,消耗太大,這時shouldRasterize = yes,下次就只是簡單的從渲染引擎的cache里讀取那張bitmap,節(jié)約系統(tǒng)資源。

而光柵化會導(dǎo)致離屏渲染,影響圖像性能,那么光柵化是否有助于優(yōu)化性能,就取決于光柵化創(chuàng)建的位圖緩存是否被有效復(fù)用,而減少渲染的頻度??梢允褂肐nstruments進(jìn)行檢測:

當(dāng)你使用光柵化時,你可以開啟“Color Hits Green and Misses Red”來檢查該場景下光柵化操作是否是一個好的選擇。
如果光柵化的圖層是綠色,就表示這些緩存被復(fù)用;如果是紅色就表示緩存會被重復(fù)創(chuàng)建,這就表示該處存在性能問題了。

注意:
對于經(jīng)常變動的內(nèi)容,這個時候不要開啟,否則會造成性能的浪費(fèi)

示例

光柵化是將一個layer預(yù)先渲染成位圖(bitmap),然后加入緩存中。如果對于陰影效果這樣比較消耗資源的靜態(tài)內(nèi)容進(jìn)行緩存,可以得到一定幅度的性能提升。demo中的這一行代碼表示將label的layer光柵化:

label.layer.shouldRasterize = YES;

注意:光柵化的核心在于緩存的思想。我們自己動手把玩一下,可以發(fā)現(xiàn)以下幾個有意思的現(xiàn)象:

1 上下微小幅度滑動時,一直是綠色
2.上下較大幅度滑動,新出現(xiàn)的label一開始是紅色,隨后變成綠色
3.如果靜止一秒鐘,剛開始滑動時會變紅。

這是因為layer進(jìn)行光柵化后渲染成位圖放在緩存中。當(dāng)屏幕出現(xiàn)滑動時,我們直接從緩存中讀取而不必渲染,所以會看到綠色。當(dāng)新的label出現(xiàn)時,緩存中沒有個這個label的位圖,所以會變成紅色。第三點(diǎn)比較關(guān)鍵,緩存中的對象有效期只有100ms,即如果在0.1s內(nèi)沒有被使用就會自動從緩存中清理出去。這就是為什么停留一會兒再滑動就會看到紅色。

光柵化的緩存機(jī)制是一把雙刃劍,先寫入緩存再讀取有可能消耗較多的時間。因此光柵化僅適用于較復(fù)雜的、靜態(tài)的效果。通過Instrument的調(diào)試發(fā)現(xiàn),這里使用光柵化經(jīng)常出現(xiàn)未命中緩存的情況,如果沒有特殊需要則可以關(guān)閉光柵化,所以我們做的第二個優(yōu)化是注釋掉下面這行代碼

//label.layer.shouldRasterize = YES;

原文,此處只為學(xué)習(xí)

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

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

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