iOS開發筆記--iOS 事件處理機制與圖像渲染過程

iOS 事件處理機制與圖像渲染過程

·iOS RunLoop都幹了什麼

·iOS 爲什麼必須在主線程中操作UI

·事件響應

·CALayer

·CADisplayLink 和 NSTimer

·iOS 渲染過程

·渲染時機

·CPU 和 GPU渲染

·Core Animation

·Facebook Pop介紹

·AsyncDisplay介紹

·參考文章

iOS RunLoop都幹了什麼

RunLoop是一個接收處理異步消息事件的循環,一個循環中:等待事件發生,然後將這個事件送到能處理它的地方。

如圖1-1所示,描述了一個觸摸事件從操作系統層傳送到應用內的main runloop中的簡單過程。

圖1-1

簡單的說,RunLoop是事件驅動的一個大循環,如下代碼所示

<code class="hljs cs has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> main(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> argc, <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">char</span> * argv[]) {
     <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//程序一直運行狀態</span>
     <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">while</span> (AppIsRunning) {
          <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//睡眠狀態,等待喚醒事件</span>
          id whoWakesMe = SleepForWakingU  p();
          <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//得到喚醒事件</span>
          id <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">event</span> = GetEvent(whoWakesMe);
          <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//開始處理事件</span>
          HandleEvent(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">event</span>);
     }
     <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">return</span> <span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span>;
}</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li><li style="box-sizing: border-box; padding: 0px 5px;">12</li></ul>

RunLoop主要處理以下6類事件:

<code class="hljs cs has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__();
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__();
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__();
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__();
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__();
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span> __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__();</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li></ul>

1.Observer事件,runloop中狀態變化時進行通知。(微信卡頓監控就是利用這個事件通知來記錄下最近一次main runloop活動時間,在另一個check線程中用定時器檢測當前時間距離最後一次活動時間過久來判斷在主線程中的處理邏輯耗時和卡主線程)。這裏還需要特別注意,CAAnimation是由RunloopObserver觸發回調來重繪,接下來會講到。

2.Block事件,非延遲的NSObject PerformSelector立即調用,dispatch_after立即調用,block回調。

3.Main_Dispatch_Queue事件:GCD中dispatch到main queue的block會被dispatch到main loop執行。

4.Timer事件:延遲的NSObject PerformSelector,延遲的dispatch_after,timer事件。

5.Source0事件:處理如UIEvent,CFSocket這類事件。需要手動觸發。觸摸事件其實是Source1接收系統事件後在回調 __IOHIDEventSystemClientQueueCallback() 內觸發的 Source0,Source0 再觸發的 _UIApplicationHandleEventQueue()。source0一定是要喚醒runloop及時響應並執行的,如果runloop此時在休眠等待系統的 mach_msg事件,那麼就會通過source1來喚醒runloop執行。

6.Source1事件:處理系統內核的mach_msg事件。(推測CADisplayLink也是這裏觸發)。

RunLoop執行順序的僞代碼

<code class="hljs cs has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">SetupThisRunLoopRunTimeoutTimer(); <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// by GCD timer</span>
<span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//通知即將進入runloop__CFRUNLLOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(KCFRunLoopEntry);</span>
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">do</span> {
     __CFRunLoopDoObservers(kCFRunLoopBeforeTimers);
     __CFRunLoopDoObservers(kCFRunLoopBeforeSources);
     __CFRunLoopDoBlocks();  <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//一個循環中會調用兩次,確保非延遲的NSObject PerformSelector調用和非延遲的dispatch_after調用在當前runloop執行。還有回調block</span>
     __CFRunLoopDoSource0(); <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//例如UIKit處理的UIEvent事件</span>
     CheckIfExistMessagesInMainDispatchQueue(); <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//GCD dispatch main queue</span>
     __CFRunLoopDoObservers(kCFRunLoopBeforeWaiting); <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//即將進入休眠,會重繪一次界面</span>
     <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">var</span> wakeUpPort = SleepAndWaitForWakingUpPorts();
     <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// mach_msg_trap,陷入內核等待匹配的內核mach_msg事件</span>
     <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// Zzz...</span>
     <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// Received mach_msg, wake up</span>
     __CFRunLoopDoObservers(kCFRunLoopAfterWaiting);
     <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// Handle msgs</span>
     <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">if</span> (wakeUpPort == timerPort) {
          __CFRunLoopDoTimers();
     } <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">else</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">if</span> (wakeUpPort == mainDispatchQueuePort) {
          <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//GCD當調用dispatch_async(dispatch_get_main_queue(),block)時,libDispatch會向主線程的runloop發送mach_msg消息喚醒runloop,並在這裏執行。這裏僅限於執行dispatch到主線程的任務,dispatch到其他線程的仍然是libDispatch來處理。</span>
          __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__()
     } <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">else</span> {
          __CFRunLoopDoSource1();  <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//CADisplayLink是source1的mach_msg觸發?</span>
     }
     __CFRunLoopDoBlocks();
} <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">while</span> (!stop && !timeout);
<span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//通知observers,即將退出runloop</span>
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBERVER_CALLBACK_FUNCTION__(CFRunLoopExit);</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li><li style="box-sizing: border-box; padding: 0px 5px;">12</li><li style="box-sizing: border-box; padding: 0px 5px;">13</li><li style="box-sizing: border-box; padding: 0px 5px;">14</li><li style="box-sizing: border-box; padding: 0px 5px;">15</li><li style="box-sizing: border-box; padding: 0px 5px;">16</li><li style="box-sizing: border-box; padding: 0px 5px;">17</li><li style="box-sizing: border-box; padding: 0px 5px;">18</li><li style="box-sizing: border-box; padding: 0px 5px;">19</li><li style="box-sizing: border-box; padding: 0px 5px;">20</li><li style="box-sizing: border-box; padding: 0px 5px;">21</li><li style="box-sizing: border-box; padding: 0px 5px;">22</li><li style="box-sizing: border-box; padding: 0px 5px;">23</li><li style="box-sizing: border-box; padding: 0px 5px;">24</li><li style="box-sizing: border-box; padding: 0px 5px;">25</li><li style="box-sizing: border-box; padding: 0px 5px;">26</li><li style="box-sizing: border-box; padding: 0px 5px;">27</li></ul>

結合上面的Runloop事件執行順序,思考下面代碼邏輯中爲什麼可以標識tableview是否reload完成

<code class="hljs objectivec has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">dispatch_async</span>(dispatch_get_main_queue(), ^{
    _isReloadDone = <span class="hljs-literal" style="color: rgb(0, 102, 102); box-sizing: border-box;">NO</span>;
    [tableView reload]; <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//會自動設置tableView layoutIfNeeded爲YES,意味着將會在runloop結束時重繪table</span>
    <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">dispatch_async</span>(dispatch_get_main_queue(),^{
        _isReloadDone = <span class="hljs-literal" style="color: rgb(0, 102, 102); box-sizing: border-box;">YES</span>;
    });
});</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li></ul>

提示:這裏在GCD dispatch main queue中插入了兩個任務,一次RunLoop有兩個機會執行GCD dispatch main queue中的任務,分別在休眠前和被喚醒後。

iOS 爲什麼必須在主線程中操作UI

因爲UIKit不是線程安全的。試想下面這幾種情況:

1.兩個線程同時設置同一個背景圖片,那麼很有可能因爲當前圖片被釋放了兩次而導致應用崩潰。

2.兩個線程同時設置同一個UIView的背景顏色,那麼很有可能渲染顯示的是顏色A,而此時在UIView邏輯樹上的背景顏色屬性爲B。

3.兩個線程同時操作view的樹形結構:在線程A中for循環遍歷並操作當前View的所有subView,然後此時線程B中將某個subView直接刪除,這就導致了錯亂還可能導致應用崩潰。 

iOS4之後蘋果將大部分繪圖的方法和諸如 UIColor 和 UIFont 這樣的類改寫爲了線程安全可用,但是仍然強烈建議講UI操作保證在主線程中執行。

事件響應

蘋果註冊了一個 Source1 (基於 mach port 的) 用來接收系統事件,其回調函數爲 __IOHIDEventSystemClientQueueCallback()。

當一個硬件事件(觸摸/鎖屏/搖晃等)發生後,首先由 IOKit.framework 生成一個 IOHIDEvent 事件並由 SpringBoard 接收。

SpringBoard 只接收按鍵(鎖屏/靜音等),觸摸,加速,接近傳感器等幾種 Event,隨後用 mach port 轉發給需要的App進程。隨後蘋果註冊的那個 Source1 就會觸發回調,並調用 _UIApplicationHandleEventQueue() 進行應用內部的分發。

_UIApplicationHandleEventQueue() 會把 IOHIDEvent 處理幷包裝成 UIEvent 進行處理或分發,其中包括識別 UIGesture/處理屏幕旋轉/發送給 UIWindow 等。通常事件比如 UIButton 點擊、touchesBegin/Move/End/Cancel 事件都是在這個回調中完成的。

CALayer

在iOS當中,所有的視圖都從一個叫做UIVIew的基類派生而來,UIView可以處理觸摸事件,可以支持基於Core Graphics繪圖,可以做仿射變換(例如旋轉或者縮放),或者簡單的類似於滑動或者漸變的動畫。

CALayer類在概念上和UIView類似,同樣也是一些被層級關係樹管理的矩形塊,同樣也可以包含一些內容(像圖片,文本或者背景色),管理子圖層的位置。它們有一些方法和屬性用來做動畫和變換。和UIView最大的不同是CALayer不處理用戶的交互。CALayer並不清楚具體的響應鏈。

UIView和CALayer是一個平行的層級關係,每一個UIView都有一個CALayer實例的圖層屬性,也就是所謂的backing layer,視圖的職責就是創建並管理這個圖層,以確保當子視圖在層級關係中添加或者被移除的時候,他們關聯的圖層也同樣對應在層級關係樹當中有相同的操作。實際上這些背後關聯的Layer圖層纔是真正用來在屏幕上顯示和做動畫,UIView僅僅是對它的一個封裝,提供了一些iOS類似於處理觸摸的具體功能,以及Core Animation底層方法的高級接口。

UIView 的 Layer 在系統內部,被維護着三份同樣的樹形數據結構,分別是:

1.圖層樹(這裏是代碼可以操縱的,設置屬性的最終值會立刻在這裏更新);

2.呈現樹(是一箇中間層,系統就在這一層上更改屬性,進行各種渲染操作。比如一個動畫是更改alpha值從0到1,那麼在邏輯樹上此屬性會被立刻更新爲最終屬性1,而在動畫樹上會根據設置的動畫時間從0逐步變化到1);

3.渲染樹(其屬性值就是當前正被顯示在屏幕上的屬性值);

CADisplayLink 和 NSTimer

NSTimer 其實就是 CFRunLoopTimerRef。一個 NSTimer 註冊到 RunLoop 後,RunLoop 會爲其重複的時間點註冊好事件。

RunLoop爲了節省資源,並不會在非常準確的時間點回調這個Timer。Timer 有個屬性叫做 Tolerance (寬容度),標示了當時間點到後,容許有多少最大誤差。如果某個時間點被錯過了,例如執行了一個很長的任務,則那個時間點的回調也會跳過去,不會延後執行。

RunLoop 是用GCD的 dispatch_source_t 實現的 Timer。 當調用 NSObject 的 performSelecter:afterDelay: 後,實際上其內部會創建一個 Timer 並添加到當前線程的 RunLoop 中。所以如果當前線程沒有 RunLoop,則這個方法會失效。當調用 performSelector:onThread: 時,實際上其會創建一個 Timer 加到對應的線程去,同樣的,如果對應線程沒有 RunLoop 該方法也會失效。

CADisplayLink 是一個和屏幕刷新率(每秒刷新60次)一致的定時器(但實際實現原理更復雜,和 NSTimer 並不一樣,其內部實際是操作了一個 Source)。如果在兩次屏幕刷新之間執行了一個長任務,那其中就會有一幀被跳過去,造成界面卡頓的感覺。

iOS 渲染過程 
圖2-1 
通常來說,計算機系統中 CPU、GPU、顯示器是以上面這種方式協同工作的。CPU 計算好顯示內容提交到 GPU,GPU 渲染完成後將渲染結果放入幀緩衝區,隨後視頻控制器會按照 VSync 信號如下圖1-4所示,逐行讀取幀緩衝區的數據,經過可能的數模轉換傳遞給顯示器顯示。

圖2-2 
在 VSync 信號到來後,系統圖形服務會通過 CADisplayLink 等機制通知 App,App 主線程開始在 CPU 中計算顯示內容,比如視圖的創建、佈局計算、圖片解碼、文本繪製等。隨後 CPU 會將計算好的內容提交到 GPU 去,由 GPU 進行變換、合成、渲染。隨後 GPU 會把渲染結果提交到幀緩衝區去,等待下一次 VSync 信號到來時顯示到屏幕上。由於垂直同步的機制,如果在一個 VSync 時間內,CPU 或者 GPU 沒有完成內容提交,則那一幀就會被丟棄,等待下一次機會再顯示,而這時顯示屏會保留之前的內容不變。這就是界面卡頓的原因。從上圖中可以看到,CPU 和 GPU 不論哪個阻礙了顯示流程,都會造成掉幀現象。所以開發時,也需要分別對 CPU 和 GPU 壓力進行評估和優化。

iOS 的顯示系統是由 VSync 信號驅動的,VSync 信號由硬件時鐘生成,每秒鐘發出 60 次(這個值取決設備硬件,比如 iPhone 真機上通常是 59.97)。iOS 圖形服務接收到 VSync 信號後,會通過 IPC 通知到 App 內。App 的 Runloop 在啓動後會註冊對應的 CFRunLoopSource 通過 mach_port 接收傳過來的時鐘信號通知,隨後 Source 的回調會驅動整個 App 的動畫與顯示。

Core Animation 在 RunLoop 中註冊了一個 Observer,監聽了 BeforeWaiting 和 Exit 事件。當一個觸摸事件到來時,RunLoop 被喚醒,App 中的代碼會執行一些操作,比如創建和調整視圖層級、設置 UIView 的 frame、修改 CALayer 的透明度、爲視圖添加一個動畫;這些操作最終都會被 CALayer 標記,並通過 CATransaction 提交到一箇中間狀態去。當上面所有操作結束後,RunLoop 即將進入休眠(或者退出)時,關注該事件的 Observer 都會得到通知。這時 Core Animation 註冊的那個 Observer 就會在回調中,把所有的中間狀態合併提交到 GPU 去顯示;如果此處有動畫,通過 DisplayLink 穩定的刷新機制會不斷的喚醒runloop,使得不斷的有機會觸發observer回調,從而根據時間來不斷更新這個動畫的屬性值並繪製出來。

爲了不阻塞主線程,Core Animation 的核心是 OpenGL ES 的一個抽象物,所以大部分的渲染是直接提交給GPU來處理。 而Core Graphics/Quartz 2D的大部分繪製操作都是在主線程和CPU上同步完成的,比如自定義UIView的drawRect裏用CGContext來畫圖。

渲染時機

上面已經提到過:Core Animation 在 RunLoop 中註冊了一個 Observer 監聽 BeforeWaiting(即將進入休眠) 和 Exit (即將退出Loop) 事件 。當在操作 UI 時,比如改變了 Frame、更新了 UIView/CALayer 的層次時,或者手動調用了 UIView/CALayer 的 setNeedsLayout/setNeedsDisplay方法後,這個 UIView/CALayer 就被標記爲待處理,並被提交到一個全局的容器去。當Oberver監聽的事件到來時,回調執行函數中會遍歷所有待處理的UIView/CAlayer 以執行實際的繪製和調整,並更新 UI 界面。

這個函數內部的調用棧大概是這樣的:

<code class="hljs css has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">_<span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv</span>()
    <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">QuartzCore</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">:CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Transaction</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::observer_callback</span>:
        <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Transaction</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::commit()</span>;
            <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Context</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::commit_transaction()</span>;
                <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Layer</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::layout_and_display_if_needed()</span>;
                    <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Layer</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::layout_if_needed()</span>;
                          <span class="hljs-attr_selector" style="color: rgb(0, 136, 0); box-sizing: border-box;">[CALayer layoutSublayers]</span>;
                          <span class="hljs-attr_selector" style="color: rgb(0, 136, 0); box-sizing: border-box;">[UIView layoutSubviews]</span>;
                    <span class="hljs-tag" style="color: rgb(0, 0, 0); box-sizing: border-box;">CA</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::Layer</span><span class="hljs-pseudo" style="color: rgb(0, 0, 0); box-sizing: border-box;">::display_if_needed()</span>;
                          <span class="hljs-attr_selector" style="color: rgb(0, 136, 0); box-sizing: border-box;">[CALayer display]</span>;
                          <span class="hljs-attr_selector" style="color: rgb(0, 136, 0); box-sizing: border-box;">[UIView drawRect]</span>;</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li></ul>

CPU 和 GPU渲染

OpenGL中,GPU屏幕渲染有以下兩種方式:

1.On-Screen Rendering

意爲當前屏幕渲染,指的是GPU的渲染操作是在當前用於顯示的屏幕緩衝區中進行。

2.Off-Screen Rendering

意爲離屏渲染,指的是GPU在當前屏幕緩衝區以外新開闢一個緩衝區進行渲染操作。

按照這樣的說法,如果將不在GPU的當前屏幕緩衝區中進行的渲染都稱爲離屏渲染,那麼就還有另一種特殊的“離屏渲染”方式:CPU渲染。如果我們重寫了drawRect方法,並且使用任何Core Graphics的技術進行了繪製操作,就涉及到了CPU渲染。整個渲染過程由CPU在App內同步地完成,渲染得到的bitmap最後再交由GPU用於顯示。

相比於當前屏幕渲染,離屏渲染的代價是很高的,主要體現在兩個方面:

1.創建新緩衝區

要想進行離屏渲染,首先要創建一個新的緩衝區。

2.上下文切換

離屏渲染的整個過程,需要多次切換上下文環境:先是從當前屏幕(On-Screen)切換到離屏(Off-Screen);等到離屏渲染結束以後,將離屏緩衝區的渲染結果顯示到屏幕上有需要將上下文環境從離屏切換到當前屏幕。而上下文環境的切換是要付出很大代價的。

設置了以下屬性時,都會觸發離屏繪製:

1.shouldRasterize(光柵化)

2.masks(遮罩)

3.shadows(陰影)

4.edge antialiasing(抗鋸齒)

5.group opacity(不透明) 

需要注意的是,如果shouldRasterize被設置成YES,在觸發離屏繪製的同時,會將光柵化後的內容緩存起來,如果對應的layer及其sublayers沒有發生改變,在下一幀的時候可以直接複用。這將在很大程度上提升渲染性能。

而其它屬性如果是開啓的,就不會有緩存,離屏繪製會在每一幀都發生。

在開發時需要根據實際情況來選擇最優的實現方式,儘量使用On-Screen Rendering。簡單的Off-Screen Rendering可以考慮使用Core Graphics讓CPU來渲染。

Core Animation

1.隱式動畫

隱式動畫是系統框架自動完成的。Core Animation在每個runloop週期中自動開始一次新的事務,即使你不顯式的用[CATransaction begin]開始一次事務,任何在一次runloop循環中屬性的改變都會被集中起來,然後做一次0.25秒的動畫。

在iOS4中,蘋果對UIView添加了一種基於block的動畫方法:+animateWithDuration:animations:。

這樣寫對做一堆的屬性動畫在語法上會更加簡單,但實質上它們都是在做同樣的事情。

CATransaction的+begin和+commit方法在+animateWithDuration:animations:內部自動調用,這樣block中所有屬性的改變都會被事務所包含。

Core Animation通常對CALayer的所有屬性(可動畫的屬性)做動畫,但是UIView是怎麼把它關聯的圖層的這個特性關閉了呢?

每個UIView對它關聯的圖層都扮演了一個委託,並且提供了-actionForLayer:forKey的實現方法。當不在一個動畫塊的實現中,UIView對所有圖層行爲返回nil,但是在動畫block範圍之內,它就返回了一個非空值。

<code class="hljs objectivec has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">@interface</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(102, 0, 102);">ViewController</span> ()</span>
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">@property</span> (<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">nonatomic</span>, <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">weak</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">IBOutlet</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">UIView</span> *layerView;
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">@end</span>
<span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">@implementation</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(102, 0, 102);">ViewController</span></span>
- (<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">void</span>)viewDidLoad
{
    [<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">super</span> viewDidLoad];
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//test layer action when outside of animation block</span>
    <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">NSLog</span>(@<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"Outside: %@"</span>, [<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">self</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layerView</span> actionForLayer:<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">self</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layerView</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layer</span> forKey:@<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"backgroundColor"</span>]);
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//begin animation block</span>
    [<span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">UIView</span> beginAnimations:<span class="hljs-literal" style="color: rgb(0, 102, 102); box-sizing: border-box;">nil</span> context:<span class="hljs-literal" style="color: rgb(0, 102, 102); box-sizing: border-box;">nil</span>];
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//test layer action when inside of animation block</span>
    <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">NSLog</span>(@<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"Inside: %@"</span>, [<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">self</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layerView</span> actionForLayer:<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">self</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layerView</span><span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.layer</span> forKey:@<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"backgroundColor"</span>]);
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//end animation block</span>
    [<span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">UIView</span> commitAnimations];
}
<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">@end</span>
$ LayerTest[<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">21215</span>:c07] Outside: $ LayerTest[<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">21215</span>:c07] Inside:</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li><li style="box-sizing: border-box; padding: 0px 5px;">12</li><li style="box-sizing: border-box; padding: 0px 5px;">13</li><li style="box-sizing: border-box; padding: 0px 5px;">14</li><li style="box-sizing: border-box; padding: 0px 5px;">15</li><li style="box-sizing: border-box; padding: 0px 5px;">16</li><li style="box-sizing: border-box; padding: 0px 5px;">17</li><li style="box-sizing: border-box; padding: 0px 5px;">18</li></ul>

2.顯式動畫

Core Animation提供的顯式動畫類型,既可以直接對退曾屬性做動畫,也可以覆蓋默認的圖層行爲。

我們經常使用的CABasicAnimation,CAKeyframeAnimation,CATransitionAnimation,CAAnimationGroup等都是顯式動畫類型,這些CAAnimation類型可以直接提交到CALayer上。

無論是隱式動畫還是顯式動畫,提交到layer後,經過一系列處理,最後都經過上文描述的繪製過程最終被渲染出來。

Facebook Pop介紹

在計算機的世界裏面,其實並不存在絕對連續的動畫,你所看到的屏幕上的動畫本質上都是離散的,只是在一秒的時間裏面離散的幀多到一定的數量人眼就覺得是連續的了,

在iOS中,最大的幀率是60幀每秒。 iOS提供了Core Animation框架,只需要開發者提供關鍵幀信息,比如提供某個animatable屬性終點的關鍵幀信息,然後中間的值則通過一定的算法進行插值計算,從而實現補間動畫。 Core Aniamtion中進行插值計算所依賴的時間曲線由CAMediaTimingFunction提供。

Pop Animation在使用上和Core Animation很相似,都涉及Animation對象以及Animation的載體的概念,不同的是Core Animation的載體只能是CALayer,而Pop Animation可以是任意基於NSObject的對象。當然大多數情況Animation都是界面上顯示的可視的效果,所以動畫執行的載體一般都直接或者間接是UIView或者CALayer。

但是如果你只是想研究Pop Animation的變化曲線,你也完全可以將其應用於一個普通的數據對象。Pop Animation應用於CALayer時,在動畫運行的任何時刻,layer和其presentationLayer的相關屬性值始終保持一致,而Core Animation做不到。 Pop Animation可以應用任何NSObject的對象,而Core Aniamtion必須是CALayer。

下面這個例子就是自定義Pop readBlock和writeBlock處理自定義的動畫屬性:

<code class="hljs objectivec has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">prop = [POPAnimatableProperty propertyWithName:@<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"com.foo.radio.volume"</span> initializer:^(POPMutableAnimatableProperty *prop) {
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// read value</span>
    prop<span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.readBlock</span> = ^(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">id</span> obj, <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">CGFloat</span> values[]) {
        values[<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span>] = [obj volume];
    };
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// write value</span>
    prop<span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.writeBlock</span> = ^(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">id</span> obj, <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">const</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">CGFloat</span> values[]) {
        [obj setVolume:values[<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span>]];
    };
    <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">// dynamics threshold</span>
    prop<span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.threshold</span> = <span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0.01</span>;
}];
POPSpringAnimation *anim = [POPSpringAnimation animation];
anim<span class="hljs-variable" style="color: rgb(102, 0, 102); box-sizing: border-box;">.property</span> = prop;</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li><li style="box-sizing: border-box; padding: 0px 5px;">4</li><li style="box-sizing: border-box; padding: 0px 5px;">5</li><li style="box-sizing: border-box; padding: 0px 5px;">6</li><li style="box-sizing: border-box; padding: 0px 5px;">7</li><li style="box-sizing: border-box; padding: 0px 5px;">8</li><li style="box-sizing: border-box; padding: 0px 5px;">9</li><li style="box-sizing: border-box; padding: 0px 5px;">10</li><li style="box-sizing: border-box; padding: 0px 5px;">11</li><li style="box-sizing: border-box; padding: 0px 5px;">12</li><li style="box-sizing: border-box; padding: 0px 5px;">13</li><li style="box-sizing: border-box; padding: 0px 5px;">14</li></ul>

Pop實現依賴的核心就是CADisplayLink。

最後附上一篇介紹Facebook Pop如何使用的文章 《Introducing Facebook Pop》

AsyncDisplay介紹

阻塞主線程的繪製任務主要是這三大類:Layout計算視圖佈局文本寬高、Rendering文本渲染圖片解碼圖片繪製、UIKit對象創建更新釋放。除了UIKit和CoreAnimation相關操作必須在主線程中進行,其他的都可以挪到後臺線程異步執行。

AsyncDisplay通過抽象UIView的關係創建了ASDisplayNode類,ASDisplayNode是線程安全的,它可以在後臺線程創建和修改。Node 剛創建時,並不會在內部新建 UIView 和 CALayer,直到第一次在主線程訪問 view 或 layer 屬性時,它纔會在內部生成對應的對象。當它的屬性(比如frame/transform)改變後,它並不會立刻同步到其持有的 view 或 layer 去,而是把被改變的屬性保存到內部的一箇中間變量,稍後在需要時,再通過某個機制一次性設置到內部的 view 或 layer。從而可以實現異步併發操作。

AsyncDisplay實現依賴如同Core Animation在runloop中註冊observer事件來觸發。

同樣附上一篇介紹AsyncDisplay的好文 《iOS保持界面流暢的技巧和AsyncDisplay介紹》

參考文章 
runloop原理 (https://github.com/ming1016/study/wiki/CFRunLoop)

深入理解runloop (http://blog.ibireme.com/2015/05/18/runloop/)

線程安全類的設計 (http://objccn.io/issue-2-4/)

iOS保持界面流暢的技巧和AsyncDisplay介紹 (http://blog.ibireme.com/2015/11/12/smooth_user_interfaces_for_ios/

離屏渲染 (http://foggry.com/blog/2015/05/06/chi-ping-xuan-ran-xue-xi-bi-ji/)

ios核心動畫高級技巧 (https://zsisme.gitbooks.io/ios-/content/index.html)

該文章轉自:http://www.cocoachina.com/ios/20151203/14549.html

0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章