Why isn't this CALayer displaying an image?
Can you guys explain why this code is not showing the image?
CALayer *layerBack = [CALayer layer];
addedObject = [[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: @"%@%d", PREFIX, number] ofType:@"png"]];
layerBack.bounds=CGRectMake(0.0f,0.0f,selectedImage.size.height,selectedImage.size.width);
layerBack.position=CGPointMake(200,200);
layerBack.contents = (id)selectedImage.CGImage;
// in theory I think this line should be equal to selectedImage.CGImage, but when I do that, Xcode shows me an error!
[self.view.layer addSublayer:layerBack];
[layerBack display];
This quartz material is driving me crazy! Please, help!
Yes, the image is up and running, but all I see after this code is a blank screen.
source to share
I am assuming that this code is from your view controller and that its view was built correctly before that (otherwise you will be sending messages to zero). Also, I assume the addedObject
above is what you mean selectedImage
. One thing that jumps out at me is that
[layerBack display];
should be replaced with
[layerBack setNeedsDisplay];
From CALayer's documentation regarding-display:
You don't have to call this method directly.
For more information on setting the content of layers like this, see the Providing Layer Content section in the Basic Animation Programming Guide.
source to share
Well first of all, I think you need to cast the CGImage to id.
layerBack.contents = (id)selectedImage.CGImage;
And secondly, I think you need to add a layer to the views content layer
[self.view.layer addSublayer:layerBack];
But I always used my own UIViews + (Class) layerClass; to create custom layers that have composited their own sublayers, but maybe that's just me.
source to share