Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

srg39

macrumors newbie
Original poster
May 7, 2009
2
0
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.

Code:
-(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);
	Layer1.name = @"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:

Code:
- (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?

Thanks,
srg39.
 
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.
 
Thanks for the help kainjow!

I've added two lines to -setupLayers:

Code:
	Layer1.bounds = CGRectMake(0, 0, 320, 480);
	Layer1.position = CGPointMake(0,0);

and removed two lines from -drawLayerInContext:

Code:
	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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.