覆盖 drawRect 时的黑色视图:

Black view when overriding drawRect:

所以我正在关注 simple tutorial 以使用户能够在视图上绘图并且我已经使代码正常工作。但我想向视图添加背景图像,以便用户在该图像上绘图。

我遇到的问题是我的 PaintView 背景总是黑色,但 PaintView 后面有非黑色视图。

我认为问题是 CGImageRef cacheImage = CGBitmapContextCreateImage(cacheContext); 在我想要创建透明背景时创建了黑色背景。

所以现在的问题是,我怎样才能解决这个问题,使我的 PaintView 的背景是透明的(或者我从 CGBitmapContextCreateImage 获得的图像,具体取决于问题所在) .

教程中建议的代码:

- (void) drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef cacheImage = CGBitmapContextCreateImage(cacheContext);
    CGContextDrawImage(context, self.bounds, cacheImage);
    CGImageRelease(cacheImage);
}

我用来绘制图像的代码:

- (void) drawRect:(CGRect)rect {
    if(_snapshot != nil) {
        [_snapshot drawInRect:rect];
    }
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef cacheImage = CGBitmapContextCreateImage(cacheContext);
    CGContextDrawImage(context, self.bounds, cacheImage);
    CGImageRelease(cacheImage);
}

其中_snapshot是我要显示的UIImage

我的下一个想法是,当我创建 cacheContext 时,我用黑色背景初始化它,它应该是透明的。任何想法如何做到这一点?

编辑:我已经从 drawRect 中删除了涉及 CGContext 的所有内容(只留下我的图像),它可以绘制图像,但包括 CGContext 调用,它呈现为黑色.

PS:我目前正在使用Xamarin,但我在Objective-C中询问过,因为Xamarin重命名了很多与CGContexts相关的东西。我会看C#,Objective-C和Swift,所以你可以用任何语言回答。

This answer 解决了我的问题:

CGBitmapContext supports only certain possible pixel formats. You probably want kCGImageAlphaPremultipliedLast.