【问题标题】:Delegate method drawLayer: inContext not called委托方法drawLayer:未调用inContext
【发布时间】:2012-01-25 09:25:45
【问题描述】:

我很难在我的代码中找到缺失的部分。我有一个派生自 UIView(customView) 的类,还有一个派生自 CALayer (customLayer) 的类并实现了 CALayer 的 drawLayer:inContext 委托方法class.I 这样做是因为我想将 customLayer 用作剪贴蒙版,因此我需要 drawLayer: inContext 方法,该方法在我启动应用程序时不会被调用。 这是我的代码的 sn-p

@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor lightGrayColor]; 
        // Initialization code
        CustomLayer *customLayer= [CALayer layer];     
        customLayer.backgroundColor= [UIColor colorWithRed:0 green:0.6 blue:0.2  alpha:0.4].CGColor;
        customLayer.frame = self.bounds;
        customLayer.delegate=customLayer;
        [customLayer setNeedsDisplay];
        [self.layer addSublayer:customLayer];
     }
  return self;
}

和 customLayer 实现:

@implementation CustomLayer

-(void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    NSLog(@"drawLayer:inContext");
    CGContextBeginPath (ctx);
    CGContextAddEllipseInRect(ctx, self.frame);
    CGContextClosePath (ctx);
    CGContextClip (ctx);
}

我真的不知道发生了什么。任何建议将不胜感激。

【问题讨论】:

    标签: objective-c core-graphics calayer quartz-2d


    【解决方案1】:

    根据 cmets 中的对话进行更新

    首先,这一行:

    CustomLayer *customLayer= [CALayer layer];     
    

    需要使用你的 CustomLayer:

    CustomLayer *customLayer= [CustomLayer layer];     
    

    也就是说,将 customLayer 设置为其自己的委托有点奇怪,您实际上可能会遇到阻止这种情况的代码。

    您是否尝试过使用- (void)drawInContext:(CGContextRef)ctx 方法?通常,每个 CALayerDelegate 方法都有一个对应的 CALayer 方法,您可以在子类中重写。

    -(void) drawInContext:(CGContextRef)ctx
    {
        NSLog(@"drawLayer:inContext");
        CGContextBeginPath (ctx);
        CGContextAddEllipseInRect(ctx, self.frame);
        CGContextClosePath (ctx);
        CGContextClip (ctx);
    
        // Note: this is where your original code ended, you have successfully set up a clipping path, but you haven't drawn anything to actually get clipped!
        CGContextSetRGBFillColor(context, 0, 0.6, 0.2, 0.4);
        CGContextFillRect(context, self.bounds);
    }
    

    另外,您是否设置了 CustomLayer 实例的框架(边界/位置//中心)?我看到您将它添加到层层次结构中,但默认大小为 0,0。

    【讨论】:

    • 是的,我试过了,但还是不行。是的,我把框架设置为我的帖子中的错字。
    • 几分钟前我才意识到你实际上并没有在 -draw... 方法中绘制任何东西,你只是在设置一个剪切路径。我在上面更新了我的答案,如果你这样做,你会得到一个椭圆吗?注意:我怀疑你最终想在这里使用 CALayer.mask,而不是 CoreGraphics 剪切路径。
    • 我看到了你的笔记,但这并不能解决问题。无论我尝试什么方法都不会被调用。
    • 我的想法来自这里:developer.apple.com/library/ios/#documentation/GraphicsImaging/…查看图3-3。和清单3-1 *是背景颜色显示,图层被添加但不被剪裁。
    • CustomLayer *customLayer= [CALayer layer]; 必须是 CustomLayer *customLayer= [CustomLayer layer]; ,否则您的子类将不会被实例化。我会把它移到聊天中,以便我们讨论,但遗憾的是我还不能这样做。一旦我更改了该行,我的 -drawInContext: 方法就会被调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多