2010-05-05 20 views
3

我有一個包含許多CALayers的NSView。當用戶正在編輯文檔時,這些CALayers會對所有編輯進行動畫處理。我正在嘗試爲我的應用程序實施打印,但我在正確打印這些CALayers時遇到了一些問題。打印CALayers

一些CALayers邊界佔用整個NSView,不需要佈置,因爲它們的位置從不改變。但是,我也有一個包含約20個小CALayer的CALayer。這些CALayers在正常編輯過程中對其位置變化進行動畫處理。但是,當試圖打印NSView時,這些小型CALayer永遠無法正確佈局。我想知道是否有什麼特別的我必須做,以確保這些圖層正確定位,並允許正確繪製/打印NSView。

有沒有人有印刷Core Animation支持的NSView的經驗?任何建議表示讚賞。

回答

5

爲了解決佈局問題,以及使用-renderInContext:繪製圖層層次結構不保留矢量元素的事實,我們在Core Plot framework中對CALayer進行了分類。 CPLayer子類會覆蓋默認的-drawInContext:方法,以調用我們自定義的-renderAsVectorInContext:方法(在這裏我們執行所有圖層的Core Graphics繪圖)。爲了產生用於打印的PDF上下文(或類似的),我們然後調用一個自定義的方法用下面的代碼:

-(void)recursivelyRenderInContext:(CGContextRef)context 
{ 
    // render self 
    CGContextSaveGState(context); 

    [self applyTransform:self.transform toContext:context]; 

    self.renderingRecursively = YES; 
    if (!self.masksToBounds) { 
     CGContextSaveGState(context); 
    } 
    [self renderAsVectorInContext:context]; 
    if (!self.masksToBounds) { 
     CGContextRestoreGState(context); 
    } 
    self.renderingRecursively = NO; 

    // render sublayers 
    for (CALayer *currentSublayer in self.sublayers) { 
     CGContextSaveGState(context); 

     // Shift origin of context to match starting coordinate of sublayer 
     CGPoint currentSublayerFrameOrigin = currentSublayer.frame.origin; 
     CGRect currentSublayerBounds = currentSublayer.bounds; 
     CGContextTranslateCTM(context, 
           currentSublayerFrameOrigin.x - currentSublayerBounds.origin.x, 
           currentSublayerFrameOrigin.y - currentSublayerBounds.origin.y); 
     [self applyTransform:self.sublayerTransform toContext:context]; 
     if ([currentSublayer isKindOfClass:[CPLayer class]]) { 
      [(CPLayer *)currentSublayer recursivelyRenderInContext:context]; 
     } else { 
      if (self.masksToBounds) { 
       CGContextClipToRect(context, currentSublayer.bounds); 
      } 
      [currentSublayer drawInContext:context]; 
     } 
     CGContextRestoreGState(context); 
    } 
    CGContextRestoreGState(context); 
} 

這又通過並使得每個層在平坦核心圖形上下文,保存位置,旋轉和其他變換同時將所有元素渲染爲尖銳的矢量。

當試圖呈現圖層時,需要注意的另外一件事是表示圖層層次結構的狀態可能與您的內部圖層層次結構不同。您可能已應用動畫來移動圖層,但圖層的position屬性可能尚未更改爲匹配。在這種情況下,您應該確保自己動畫屬性,以便值始終保持同步,或者在動畫完成後設置圖層中的值。

0

最後我看了一下,無法正確打印CALayers。在我看來,Core Animation只是爲了屏幕而設計的,而不是用於打印(這與它最初爲iPhone設計的事實似乎一致)。

我很想知道我錯了。