Can't draw on my CALayer!

Discussion in 'iOS Programming' started by srg39, May 7, 2009.

  1. srg39 macrumors newbie

    May 7, 2009
    Hi All,

    I'm new to mac programming and I'm having some problems trying to draw on a CALayer. I'm creating my layer in a viewcontroller using the function (below). This is called in the -viewDidLoad of my viewcontroller.

    -(void)setupLayers {
    	myHelper = [[ViewDelegateHelper alloc] init]; //an object containing only my drawLayerinContext delegate
    	//Layer 1
    	Layer1 = [CALayer layer];
    	Layer1.frame = CGRectMake(50.0, 50.0, 50.0, 50.0); = @"BarOneLayer";
    	[Layer1 setDelegate:myHelper];
    	[[self.view layer] addSublayer:Layer1];
    myHelper is an object that only contains the delegate (below) I'm using to do the drawing:

    - (void)drawLayer:(CALayer *)myLayer inContext:(CGContextRef)myContext{
    	CALayer *theLayer = [CALayer layer];
    	*theLayer = *myLayer;
    	CGRect rectOne = CGRectMake(40, 150, 50, 300 );
    	theLayer.frame = CGRectMake(0, 0, 320,480 );
    	//change background layer color
    	float components[4] = {0, 0, 1, 0.5};
    	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    	CGColorRef transparentColor = CGColorCreate( colorSpace, components);
    	theLayer.backgroundColor = transparentColor;
    	//draw rectangle on layer
    	CGContextSetRGBFillColor (myContext, 1, 1, 0, 1);
    	CGContextFillRect (myContext, rectOne);
    When I run the app, I see the new background color of the layer but I can't seem to be able to get it to draw my rectangle. Does anyone know what I'm missing?

  2. kainjow Moderator emeritus


    Jun 15, 2000
    Where is barRect and are you sure it's within the layer's bounds? Can you confirm the draw method is being called?

    I'm not following what you're doing with theLayer. I think that's just unnecessary. Use myLayer directly.
  3. srg39 thread starter macrumors newbie

    May 7, 2009
    Thanks for the help kainjow!

    I've added two lines to -setupLayers:

    	Layer1.bounds = CGRectMake(0, 0, 320, 480);
    	Layer1.position = CGPointMake(0,0);
    and removed two lines from -drawLayerInContext:

    	CALayer *theLayer = [CALayer layer];
    	*theLayer = *myLayer;
    and it's all working fine now.

    I had convinced myself that I was looking for something a lot more subtle. All I was missing was setting the bounds of the Layer.

Share This Page