Iphone – Removing image background in UIImageView at runtime

cocoa-touchinterface-builderiphoneuiimageuiimageview

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?

Best Answer

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.