CGLayer對(duì)象允許使用layers進(jìn)行繪制。
適合使用layer繪制的場(chǎng)景:
1.高質(zhì)量的離屏渲染重用。繪制到layer上的時(shí)候不需要知道顏色空間和設(shè)備獨(dú)立信息。
2.重復(fù)繪制。如圖12-1.當(dāng)你重復(fù)繪制包括CGPath,CGShading,CGPDFPage對(duì)象時(shí),繪制到layer會(huì)提高執(zhí)行效率。layer不止適用于離屏渲染,比如PDF graphics context。

3.緩存。當(dāng)你繪制在緩存時(shí),使用layer代替位圖上下文。
How Layer Drawing Works layer如何工作
layer? ,CGLayerRef格式,被設(shè)計(jì)為最佳性能。For this reason a layer is typically a better choice for offscreen drawing than a bitmap graphics context is.
所有的Quartz都是繪制在上下文中的,layer也不例外??匆桓眑ayer 繪制的工序圖:

開始,你需要通過調(diào)用方法CGLayerCreateWithContext.創(chuàng)建一個(gè)CGLayer對(duì)象。本文中使用的是一個(gè)窗口上下文。Quartz創(chuàng)建一個(gè)layer的時(shí)候就已經(jīng)獲得了上下文的所有特性---分辨率,顏色空間和圖形狀態(tài)設(shè)置等等。如果不想使用圖形上下文的大小,可是設(shè)置你想要的。
繪制layer之前 你需要獲得與layer 有聯(lián)系的上下文,調(diào)用方法CGLayerGetContext.CGLayer上下文被CPU緩存起來。
當(dāng)你準(zhǔn)備好layer的內(nèi)容的時(shí)候,你調(diào)用方法CGContextDrawLayerInRectorCGContextDrawLayerAtPoint,繪制layer到圖形上下文。
注意點(diǎn):使用透明層實(shí)現(xiàn)陰影組團(tuán)效果。使用CGLayer實(shí)現(xiàn)離屏渲染或者重復(fù)繪制。
Drawing with a Layer
1.Create a CGLayer Object Initialized with an Existing Graphics Context
2.Get a Graphics Context for the Layer
3.Draw to the CGLayer Graphics Context
4.Draw the Layer to the Destination Graphics Context
SeeExample: Using Multiple CGLayer Objects to Draw a Flagfor a detailed code example.
1、調(diào)用方法CGLayerCreateWithContext傳入三個(gè)參數(shù),實(shí)例化layer。:上下文,size,一個(gè)輔助字典。
2、調(diào)用方法 CGLayerGetContext 或者layer的上下文。
3、繪制the CGLayer Graphics Context 。調(diào)用方法GContextFillRect,比如:CGContextFillRect (myLayerContext, myRect)
4.繪制layer 到目的上下文。CGContextDrawLayerInRect/GContextDrawLayerAtPoint,
示例:美國(guó)國(guó)旗

簡(jiǎn)單分析:主要分為三塊,紅色與白色相間,藍(lán)色矩形框,50個(gè)星星。第一塊,第三塊都可是使用layer 重復(fù)繪制。
代碼片段:



