NSView中CALayers的简单示例

AP.*_*AP. 3 cocoa core-animation objective-c calayer

我正在尝试将几个CALayers添加到NSView,但显示时我的视图仍为空:

这是我的代码:

- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {

    self.layer = [CALayer layer];
    self.wantsLayer = YES;
    CALayer *newLayer = [CALayer layer];
    NSImage *image = [NSImage imageNamed:@"page.png"];
    newLayer.backgroundColor = [NSColor redColor].CGColor;
    newLayer.contents = (id)[image CGImageForProposedRect:NULL context:NULL hints:nil];
    newLayer.frame = NSMakeRect(100,100,100,100);//NSMakeRect(0,0,image.size.width,image.size.height);
    newLayer.position  = CGPointMake(20,20);
    [self.layer addSublayer:newLayer];

}
return self;
Run Code Online (Sandbox Code Playgroud)

}

有任何想法(或代码示例)来执行此任务吗?

感谢致敬,

iai*_*ain 10

设置图层的代码需要在awakeFromNib方法中,而不是在initWithFrame函数中.

解释为什么:)

在nib文件中,您的视图被标记为不需要图层,因此流程是

  • 您在initWithFrame:方法中设置图层
  • nib文件属性设置为擦除图层.

您也可以保留代码,并告诉界面构建器您的自定义视图需要一个图层.