e2l3n
e2l3n

Reputation: 535

Delegate method drawLayer: inContext not called

I'm struggling to find the missing piece in my code.I have a class which derives from UIView(customView) and also have a class that derives from CALayer (customLayer) and implements the drawLayer:inContext delegate method of the CALayer class.I do that because I want to use the customLayer as a clipping mask and so I need the drawLayer: inContext method which is not called when I start the application. Here is a snippet of my code

@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;
}

and the customLayer implementation:

@implementation CustomLayer

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

I really can't figure out what is going on.Any advices will be greatly appreciated.

Upvotes: 0

Views: 4290

Answers (1)

iccir
iccir

Reputation: 5128

Updating based on conversation in comments

First, this line:

CustomLayer *customLayer= [CALayer layer];     

needs to use your CustomLayer:

CustomLayer *customLayer= [CustomLayer layer];     

That said, setting the customLayer as its own delegate is a bit odd, you may actually be running into code preventing this.

Have you tried using the - (void)drawInContext:(CGContextRef)ctx method? Generally, each CALayerDelegate method has a corresponding CALayer method that you can override in subclasses.

-(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);
}

Also, are you setting the frame (bounds/position//center) of the CustomLayer instance? I see you adding it to the layer hierarchy, but at the default 0,0 size.

Upvotes: 3

Related Questions