4thSpace
4thSpace

Reputation: 44352

Removing image background in UIImageView at runtime

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?

Upvotes: 4

Views: 16964

Answers (2)

Ben Gotow
Ben Gotow

Reputation: 14893

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.

Upvotes: 6

MikZ
MikZ

Reputation: 364

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.

Upvotes: 2

Related Questions