Ios – How to create a UIImage with a transparent background

cgcontextiosuiimageuitableview

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?

Best Answer

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

Related Topic