views:

509

answers:

1

I often read that using CALayer rather than UIImageView is an performance boost when it comes to heavy image usage. That makes sense, because UIImageView causes 3 copies of the image in memory, which is needed for Core Animation. But in my case I dont use Core Animation.

How could I assign an UIImage (or the image data of it) to an CALayer and then display it?

+2  A: 
UIImage*    backgroundImage = [UIImage imageNamed:kBackName];
CALayer*    aLayer = [CALayer layer];
CGFloat nativeWidth = CGImageGetWidth(backgroundImage.CGImage);
CGFloat nativeHeight = CGImageGetHeight(backgroundImage.CGImage);
CGRect      startFrame = CGRectMake(0.0, 0.0, nativeWidth, nativeHeight);
aLayer.contents = (id)backgroundImage.CGImage;
aLayer.frame = startFrame;
Glenn Howes
thanks! why do you write (id)backgroundImage and not just backgroundImage? Shouldn't the compiler recognize that you have a UIImage there? Or is the CGImage property otherwise not recognized? Maybe an missing import?
HelloMoon
I tried it. The most interesting thins is missing though: How to get it on screen? I want to avoid an UIViews as much as possible.
HelloMoon
You'll need to add the CALayer as a sublayer of some UIView's layer. Each layer does not need its own view, but the layer hierarchy does need to reside in a view somewhere so that it can be drawn to the screen.
Brad Larson
The cast to id is needed because CGImageRef is not defined in the headers as descending from id, but that is how the contents property of CALayer is defined.
Glenn Howes