Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a UIImage with a transparent background

I am dynamically creating a (drawing my own custom) UIImage for the 'UIImageView' property on a UITableViewCell.

When a user selects the tableView cell, the cell background turns blue but my custom UIImage background does not - it remains white (so it is painfully clear I've got an image sitting there). I've tried various drawing approaches

// when I create the cell
cell.imageView.backgroundColor = [UIColor clearColor];
cell.imageView.opaque = NO;

// 1. when I create the UIImage - clearColor background
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillRect(context, rect);

// 2. when I create the UIImage - clear background
CGContextClearRect(context, rect);

but in both of these approaches, the background is black. The only thing that seems to work is to finishing creating the image and then apply create a 2nd image with 'CGImageCreateWithMaskingColors' based on the first image - masking out the background.

Is there a way I can "paint" a transparent background in the first place?

like image 837
Luther Baker Avatar asked Nov 22 '12 19:11

Luther Baker


1 Answers

Make sure that you are passing NO to the opaque parameter of the UIGraphicsBeginImageContextWithOptions function when you setup the image context.

like image 198
rmaddy Avatar answered Sep 29 '22 04:09

rmaddy