【发布时间】:2013-02-20 03:11:16
【问题描述】:
这让我有些痛苦......
我希望在我的应用程序中使用图层托管视图,但我遇到了这个奇怪的问题。
这是一个简单的例子。只需在 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) 处……就像它实际上并没有被绘制在黄色层内。 p>
我猜我的视图不是真正的图层托管,或者传递给图层的上下文是错误的......但为什么它会在下面?
我一定是做错了什么……
如果我在图层中添加一个 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。
雷诺
【问题讨论】:
标签: cocoa core-animation calayer nsview appkit