CALayer subclassing

Discussion in 'iOS Programming' started by MacNinja, Feb 26, 2009.

  1. MacNinja macrumors newbie

    Feb 26, 2009
    I found a couple threads about CALayer on here, but not my exact problem, so here goes. I'm trying to get my head around subclassing CALayer for drawing into a layer rather than a view. My problem is that I don't see my custom drawing, even though drawInContext: *is* called, according to breakpoint.

    @interface MyLayer : CALayer {



    @implementation MyLayer

    -(id) init {
    if (self = [super init]) {

    return self;


    -(void) drawInContext:(CGContextRef)ctx {
    CGSize size = [self bounds].size;
    CGFloat color[] = {1., 0, 0, 1};
    CGContextSetStrokeColor(ctx, color);
    CGContextSetLineWidth(ctx, 3.0);
    CGRect r = CGRectMake(10, 10, size.width - 40, size.height - 30);
    CGContextStrokeRect(ctx, r);


    I have a view-based application project, all I do is this in the ViewController .m:
    - (void)viewDidLoad {
    [super viewDidLoad];
    MyLayer* layer = [[MyLayer alloc] init];
    [layer setBounds:CGRectMake(0, 0, 200, 200)];
    [layer setPosition:CGPointMake(100,200)];
    layer.backgroundColor = [UIColor greenColor].CGColor;
    NSLog(@"MyLayer bounds: %@", NSStringFromCGRect([layer bounds]));
    NSLog(@"MyLayer position: %@", NSStringFromCGPoint([layer position]));
    NSLog(@"MyLayer anchorPoint: %@", NSStringFromCGPoint([layer anchorPoint]));

    [self.view.layer addSublayer:layer];
    [layer setNeedsDisplay];
    [layer release];

    The interesting thing is the background color green is shown! So where's my rect?

Share This Page