爲了解決佈局問題,以及使用-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
屬性可能尚未更改爲匹配。在這種情況下,您應該確保自己動畫屬性,以便值始終保持同步,或者在動畫完成後設置圖層中的值。