0

I'm trying to draw some fancy graphics on a UIButton using CoreGraphics and CALayers, but I can't get anything on a sublayer to display.

Here's how I set up my sublayer:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        CALayer *buttonLayer = self.layer;
        buttonLayer.masksToBounds = YES;
        buttonLayer.backgroundColor = [[UIColor clearColor] CGColor];
        self.myDelegate =  [[PlayerButtonLayerDelegate alloc] init];

        CALayer *customDrawn = [CALayer layer];
        customDrawn.delegate = self.myDelegate;
        customDrawn.frame = buttonLayer.frame;
        customDrawn.masksToBounds = YES;
        [buttonLayer insertSublayer:customDrawn atIndex:0];
        [customDrawn setNeedsDisplay];
    }
    return self;
}

PlayerButtonLayerDelegate just implements drawLayer: inContext: like this:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
    CGRect rectangleFrame = layer.bounds;
    UIGraphicsPushContext(context);
    UIBezierPath* rectanglePath = 
        [UIBezierPath bezierPathWithRect: rectangleFrame];
    [[UIColor redColor] setFill];
    [rectanglePath fill];
    UIGraphicsPopContext();
}

The code gets called (I can set a breakpoint or output to NSLog), but nothing gets displayed: I just have a transparent button (as indicated by the main layer), with and without any button text.

What do I have to change to "draw" on the sublayer?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Thorsten
  • 12,921
  • 17
  • 60
  • 79
  • 1
    You should set the `frame` of your sublayer to the `bounds` of the button layer, not its frame. Not sure if that's the only problem though. – omz Jun 06 '12 at 19:37
  • Doh .. :-) Can you submit this as an answer so I can +1/accept it? Obvious once someone points it out! Please let me know if there are other problems! Thanks. – Thorsten Jun 06 '12 at 19:41

1 Answers1

4
 [customDrawn setFrame:buttonLayer.bounds];
Kimpoy
  • 1,974
  • 3
  • 21
  • 38