views:

3345

answers:

2

I have a ball assigned to a UIImageView in Interface Builder. An IBOutlet from the UIImageView is wired to a corresponding UIViewController. The image has a white background. When I assign it to the UIImageView in IB, the background is transparent. In IB, I have the UIImageView set to a transparent background and aspect fill.

When I assign the UIImageView an image at runtime:

self.ball.image = ballImage; //ballImage is a UIImage
self.ball.backgroundColor = [UIColor clearColor];
self.ball.contentMode = UIViewContentModeScaleAspectFill;

the UIImageView square has a white background where the ball doesn't display. Meaning all four corners. What is the difference that the IB version doesn't show a white background at runtime and the programmatic version does?

+2  A: 

If you need to remove background programmatically you may refer to "Bitmap Images and Image Masks" guide. I have no other idea on this point...just using CGImageCreateWithMaskingColors.

In case your *.PNG (or any graphic resource file) doesn't have built-in transparency (just white background) but with IB it looks like transparent - may be alpha property less then 1 for your UIImageView and you see partially transparent image.

MikZ
+4  A: 

Hey 4thSpace,

Make sure you set self.ball.opaque = NO in addition to setting the background color to clear. Otherwise, a white background will still be drawn. I believe you have to set both of these whether you use IB or Xcode to create the view - but IB may have set them both for you.

  • Ben
Ben Gotow
Thanks on both suggestions. My fault. There was a PNG version of the JPGs that had transparent backgrounds. IB was using the PNGs while I was using the JPGs programmatically. Ugh! However, if the image doesn't have a transparent background, there isn't much you can do about it in an easy way. Opaque doesn't change it. I also tried setting opacity by including Quartz framework and self.ball.layer.opacity = 0.0f; but a no go again. Modifying the image is the easiest route.
4thSpace