我創建了CALayer子類以繪製棋盤格背景圖案。一切正常,渲染正確,但是我發現當CALayer被賦予一個大框架時,性能會急劇下降。CALayer CGPatternRef性能問題
看起來很明顯,我可以通過在drawLayer:inContext:call之外移動我的CGColorRef和CGPatternRef的分配來進行優化,但我不確定如何去做這件事,因爲兩者都依賴於CGContextRef。
就我的理解而言,CALayer的繪圖上下文實際上是由其父級NSView擁有的,並且只在繪圖期間傳遞。如果是這種情況,我如何才能最佳地優化下面的代碼?
void drawCheckerboardPattern(void *info, CGContextRef context)
{
CGColorRef alternateColor = CGColorCreateGenericRGB(1.0, 1.0, 1.0, 0.25);
CGContextSetFillColorWithColor(context, alternateColor);
CGContextAddRect(context, CGRectMake(0.0f, 0.0f, kCheckerboardSize, kCheckerboardSize));
CGContextFillPath(context);
CGContextAddRect(context, CGRectMake(kCheckerboardSize, kCheckerboardSize, kCheckerboardSize, kCheckerboardSize));
CGContextFillPath(context);
CGColorRelease(alternateColor);
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
CGFloat red = 0.0f, green = 0.0f, blue = 0.0f, alpha = 0.0f;
NSColor *originalBackgroundColor = [self.document.backgroundColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
[originalBackgroundColor getRed:&red green:&green blue:&blue alpha:&alpha];
CGColorRef bgColor = CGColorCreateGenericRGB(red, green, blue, alpha);
CGContextSetFillColorWithColor(context, bgColor);
CGContextFillRect(context, layer.bounds);
// Should we draw a checkerboard pattern?
if([self.document.drawCheckerboard boolValue])
{
static const CGPatternCallbacks callbacks = { 0, &drawCheckerboardPattern, NULL };
CGContextSaveGState(context);
CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);
CGContextSetFillColorSpace(context, patternSpace);
CGColorSpaceRelease(patternSpace);
CGPatternRef pattern = CGPatternCreate(NULL,
CGRectMake(0.0f, 0.0f, kCheckerboardSize*2, kCheckerboardSize*2),
CGAffineTransformIdentity,
kCheckerboardSize*2,
kCheckerboardSize*2,
kCGPatternTilingConstantSpacing,
true,
&callbacks);
alpha = 1.0f;
CGContextSetFillPattern(context, pattern, &alpha);
CGPatternRelease(pattern);
CGContextFillRect(context, layer.bounds);
CGContextRestoreGState(context);
}
CGColorRelease(bgColor);
}