Duck
Duck

Reputation: 36013

Why does this CALayer not display an image?

Can you guys tell why this code shows no 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 stuff is driving me crazy! Please help!

Yes, the image is there and is working, but all I see after this code is a blank screen.

Upvotes: 2

Views: 8285

Answers (4)

NonatomicRetain
NonatomicRetain

Reputation: 301

Bridge it:

layerBack.contents = (__bridge id)selectedImage.CGImage;

Upvotes: 2

mahboudz
mahboudz

Reputation: 39376

What is selectedImage and how does it relate to addedObject? From what I see, you get an image, but then add in an entirely different, unrelated image, possibly a blank one, to the layer.

Are you paying attention to messages Xcode is providing you?

Upvotes: 1

Brad Larson
Brad Larson

Reputation: 170317

I assume that this code is from your view controller and that its view has been properly constructed before this (otherwise, you'll be sending messages to nil). Also, I assume by addedObject above, you mean selectedImage. One thing that jumps out at me is that

[layerBack display];

should be replaced with

[layerBack setNeedsDisplay];

From the CALayer documentation, in regards to -display:

You should not call this method directly.

There's more on setting the content of layers like this in the "Providing Layer Content" section of the Core Animation Programming Guide.

Upvotes: 3

Glenn Howes
Glenn Howes

Reputation: 5607

Well first of all I think you have to cast the CGImage to an id.

layerBack.contents = (id)selectedImage.CGImage;

And secondly, I think you have to add the layer to the views content layer

[self.view.layer addSublayer:layerBack];

But I have always made use of my custom UIViews class's + (Class)layerClass; to generate custom layers which layout their own sublayers, but maybe that's just me.

Upvotes: 2

Related Questions