views:

228

answers:

3

I have been trying to write an image on a layer using Quartz but all I see is totally empty images... this is the code

CGContextRef context = UIGraphicsGetCurrentContext();

CGRect backRect  = CGRectMake (0, 0, image.size.width, image.size.height);

CGLayerRef backLayer = CGLayerCreateWithContext (context, image.size, NULL);
CGContextRef backContext = CGLayerGetContext (backLayer);

CGContextDrawImage(backContext, backRect, image.CGImage);

can you guys please tell me what is wrong with this code?

image is a UIImage taken with the camera.

Yes, the image is there. If I replace the above code with

UIGraphicsBeginImageContext(image.size);  
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

I see the image. But I have to have it in a layer, as it is a sprite.

A: 
  • Are you sure that the images were found in the right place?
  • Is the image format and color numbers supported by this iphone?
  • The images are not overdrawn by other drawing calls?
  • In the worst case an undetected memory leak caused the images to be overwritten in memory
codymanix
everything is there. If I precede this code with the lines UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; the image is drawn correctly.
Digital Robot
+1  A: 

You're not really doing anything with the layer you created. You should add it to the current context using CGContextDrawLayerAtPoint() or CGContextDrawLayerInRect() or ...

You could add the following:

CGContextDrawLayerInRect(context, backRect, backLayer);

or

CGContextDrawLayerAtPoint(context,CGPointZero,backLayer);
Philippe Leybaert
what about the line CGContextDrawImage(backContext, backRect, image.CGImage);? Isn't it drawing the layer on the context?
Digital Robot
No, you're drawing the image ON the new layer you created, but the layer itself should be added to the current context.
Philippe Leybaert
ah, OK. I have added the line CGContextDrawLayerAtPoint(context, CGPointMake(0,0), backLayer); at the end of the code but I am still getting empty images... all my hair is becoming gray in despair...
Digital Robot
+1  A: 

Be aware that a CGLayer is different than a CALayer. A CALayer is what can be animated around by Core Animation, where a CGLayer is just a convenience for pulling together a static 2-D Core Graphics drawing. Because you are referring to this as a sprite, I'm assuming you'll want to animate this around, so CALayer would be the better choice.

I recommend reading the Core Animation Programming Guide, particularly the section on providing layer content. CALayers will give you very good performance when it comes to animation, because they are GPU-accelerated and don't need to be redrawn every frame. Core Graphics will not give you anywhere near acceptable performance for animation, because redraws are expensive operations.

Brad Larson