首页 文章

drawLayer:inContext:使用Layer-Hosting NSView时在内容上绘制背景

提问于
浏览
0

这让我有些痛苦......

我想在我的应用程序中使用图层托管视图,我有这个奇怪的问题 .

这是一个简单的例子 . 简单地通过在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 Delegate方法:

- (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 .

雷诺

1 回答

  • 1

    得到它了 . 在这种情况下调用的上下文是CGContextRef,而不是NSGraphicsContext,我感到很困惑!

    我似乎能够通过从CGContextRef设置NSGraphicsContext来获得我需要的结果:

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

    //在此处插入绘图代码

    [NSGraphicsContext restoreGraphicsState];
    

相关问题