如何创建具有透明背景的 UIImage



我正在为UITableViewCell上的"UIImageView"属性动态创建一个(绘制我自己的自定义)UIImage。

当用户选择 tableView 单元格时,单元格背景变为蓝色,但我的自定义 UIImage 背景不会 - 它仍然是白色的(所以很明显我有一个图像坐在那里)。我尝试了各种绘图方法

// 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);

但在这两种方法中,背景都是黑色的。似乎唯一有效的方法是完成创建图像,然后基于第一张图像使用"CGImageCreateWithMaskingColors"应用创建第二张图像 - 屏蔽背景。

有没有办法首先"绘制"透明背景?

在设置图像上下文时,请确保将NO传递给UIGraphicsBeginImageContextWithOptions函数的opaque参数。

最新更新