问题
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 inNULL
as the first argument toCGBitmapContextCreate
, 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 useCGRectMake(0.f, 0.f, size.width, size.height)
.
来源:https://stackoverflow.com/questions/13552085/transparency-in-cgcontext