2013-02-20 50 views
0

這是導致我有些痛苦......drawLayer:inContext的:使用時繪製背景在內容層託管的NSView

我希望在我的應用程序使用圖層託管的觀點,我有這個奇怪的問題。

這是一個簡單的例子。只需通過Xcode的創建新項目,並進入了AddDelegate以下實現的:(添加QuartzCore到項目後):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
    NSView *thisView = [[NSView alloc] initWithFrame:CGRectInset([self.window.contentView bounds], 50, 50)]; 

    [thisView setLayer:[CALayer layer]]; 
    [thisView setWantsLayer:YES]; 
    thisView.layer.delegate = self; 

    thisView.layer.backgroundColor = CGColorCreateGenericRGB(1,1,0,1); 
    thisView.layer.anchorPoint = NSMakePoint(0.5, 0.5); 
    [self.window.contentView addSubview:thisView]; 

    //Create custom content 
    [thisView.layer display]; 
} 

我也實現以下CALayer的委託方法:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { 
    [[NSColor blueColor] setFill]; 
    NSBezierPath *theBez = [NSBezierPath bezierPathWithOvalInRect:layer.bounds]; 
    [theBez fill]; 
} 

如果我運行這段代碼,我可以看到子視圖被添加到windows contentView(大黃色矩形),我假設它是一個圖層託管視圖...我可以看到橢圓被繪成藍色,但它是下的黃色的矩形,它的原點在(0,0)在主窗口中...它就像它不是交流畫在黃色的層內。

我猜我的觀點不是真正的圖層託管,或傳遞到圖層的上下文是錯誤的......但爲什麼它會在下面?

我必須做一些錯誤的...

要繼續古怪,如果我添加一個CABasicAnimation的層,像這樣:

CABasicAnimation *myAnimation = [CABasicAnimation animation]; 
myAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; 
myAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
myAnimation.fromValue = [NSNumber numberWithFloat:0.0]; 
myAnimation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)]; 

myAnimation.duration = 1.0; 
myAnimation.repeatCount = HUGE_VALF; 

[thisView.layer addAnimation:myAnimation forKey:@"testAnimation"]; 
thisView.layer.anchorPoint = NSMakePoint(0.5, 0.5); 

的黃色背景被動畫,旋轉約它的中心,但是藍色橢圓在圖層框架內正確繪製(但也在窗口的原點外部,所以它出現了兩次),但不生成動畫。我期望橢圓隨着層的其餘部分旋轉。

我已經爲那些願意伸出援手的人制作了這個項目available here

Renaud

回答

1

明白了。我被這種情況稱爲CGContextRef而不是NSGraphicsContext的事實弄糊塗了!

我似乎能夠得到的結果,我需要從CGContextRef設置獲取到NSGraphicsContext:

NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO]; 
[NSGraphicsContext saveGraphicsState]; 

[NSGraphicsContext setCurrentContext:gc]; 

//插入繪圖這裏代碼

[NSGraphicsContext restoreGraphicsState];