Transparency in CGContext

◇◆丶佛笑我妖孽 提交于 2019-12-13 04:06:16

问题


I'm trying to set a transparent background for a CGContext but keep getting :

CGBitmapContextCreateImage: invalid context 0x0

Here's what I've got. If I switch kCGImageAlphaLast to kCGImageAlphaNoneSkipFirst it works but the alpha channel is completely ignored. I'm very new to this color & context stuff - any ideas?

-(BOOL) initContext:(CGSize)size {
int bitmapByteCount;
int bitmapBytesPerRow;

bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);

cacheBitmap = malloc( bitmapByteCount );
if (cacheBitmap == NULL){
    return NO;
}

cacheContext = CGBitmapContextCreate (NULL, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaLast);

CGContextSetRGBFillColor(cacheContext, 1.0, 1.0, 1.0f, 0.5);
CGContextFillRect(cacheContext, self.bounds);

return YES;
}

回答1:


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

(Here's an explanation of premultiplied alpha.)

Also note:

  • There is no need to malloc cacheBitmap. Since you are passing in NULL as the first argument to CGBitmapContextCreate, the bitmap context will do its own allocation.

  • Depending on your code, self.bounds may not be the correct rectangle to fill. It would be safer to use CGRectMake(0.f, 0.f, size.width, size.height).



来源:https://stackoverflow.com/questions/13552085/transparency-in-cgcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!