Search code examples
objective-cuiimageios-simulatorcalayercgimage

How to load a PNG as an opaque image within a CALayer?


I need to load a various PNG images in my app natively within a CALayer. To do this, my code is something like the following:

 CALayer *myLayer  = [[CALayer alloc] init];
 UIImage *myImage = [UIImage imageNamed:@"nonTransparentBackground"];
 [myLayer setOpaque:YES];
 [myLayer setContents:(__bridge id)[myImage CGImage]];
  • When I view the app in the simulator and select the 'Color blended layers' option, the whole layer has a reddish tint (i.e. alpha channel present so it's not opaque).
  • If I remove the image, so the layer is empty, it becomes greenish, so there's nothing wrong with the CALayer.
  • If instead of a .png, I load the image as a jpg, it also works fine and the layer is displayed as green.
  • My PNG file has no alpha channel (I've saved it with PS with transparency unchecked).
  • My guess now is that it's related to how the PNG is saved when created with the UIImage imagedNamed: method. Maybe at this moment iOS converts all PNGs so that the have an alpha channel. That's what I'm investigating at the moment.

UPDATE 15.04.2015: I created a test app that does nothing apart from load a PNG file in the backgrounds and it works which is good news. There must be something somewhere in my app causing this behaviour. Hopefully it won't take too long to identify.


Solution

  • I'm posting here in case someone has the problem in the future, but I doubt it. It turns out the problem wasn't related to my actual code but the Deployment Target. My current target is 7.1 but by changing to 8.0, it works as expected. I've no idea is that is Xcode/Simulator related or iOS related however so I'll probably stick with iOS 7 until the next update.