我有一个简单的CALayer子类(BoxLayer)和这个drawLayer方法:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
NSLog(@"drawLayer");
NSGraphicsContext *nsGraphicsContext;
nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx
flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsGraphicsContext];
// ...Draw content using NS APIs...
NSPoint origin = { 21,21 };
NSRect rect;
rect.origin = origin;
rect.size.width = 128;
rect.size.height = 128;
NSBezierPath * path;
path = [NSBezierPath bezierPathWithRect:rect];
[path setLineWidth:4];
[[NSColor whiteColor] set];
[path fill];
[[NSColor grayColor] set];
[path stroke];
[NSGraphicsContext restoreGraphicsState];
}
然后我在我的NSView子类中使用了这个awakeFromNib:
- (void)awakeFromNib {
CALayer* rootLayer = [CALayer layer];
[self setLayer:rootLayer];
[self setWantsLayer:YES];
box1 = [CALayer layer];
box1.bounds = CGRectMake(0, 0, 70, 30);
box1.position = CGPointMake(80, 80);
box1.cornerRadius = 10;
box1.borderColor = CGColorCreateGenericRGB(255, 0, 0, 1);
box1.borderWidth = 1.5;
[rootLayer addSublayer:box1];
box2 = [BoxLayer layer];
[box2 setDelegate:box2];
[box2 setNeedsDisplay];
[rootLayer addSublayer:box2];
}
我的drawLayer从未被调用,但为什么不呢?
谢谢
答案 0 :(得分:2)
可能是因为你的图层的框架似乎等于CGRectZero
,所以操作系统可能认为它是不可见的,因此它不需要绘制它。
另一方面,为什么要采用复杂的方式将图层的委托设置为自身并实施drawLayer:inContext:
而不是直接使用drawInContext:
?