gpt4 book ai didi

cocoa - 子类化 CALayer 时未调用 drawLayer

转载 作者:行者123 更新时间:2023-12-03 17:43:44 25 4
gpt4 key购买 nike

我有一个简单的 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从未被调用过,但为什么不呢?

谢谢

最佳答案

可能是因为您的图层的框架似乎等于CGRectZero,因此操作系统可能认为它是不可见的,因此不需要绘制它。

顺便说一句,为什么要采用复杂的方式将图层的委托(delegate)设置为自身并实现 drawLayer:inContext: 而不是直接使用 drawInContext:

关于cocoa - 子类化 CALayer 时未调用 drawLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com