CGbitmapcontext和alpha的问题

时间:2014-05-01 19:31:11

标签: ios objective-c uiview core-graphics

我正在尝试使用Core Graphics开发绘图应用程序。我希望背景为alpha,而不是黑色。我尝试使用所有不同类型的bitmapinfo类型但没有成功。 kCGImageAlphaPremultipliedLast也不起作用。任何人都知道如何解决这个问题?

- (BOOL) initContext:(CGSize)size {

    int bitmapByteCount;
    int bitmapBytesPerRow;

    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow = (size.width * 4);
    bitmapByteCount = (bitmapBytesPerRow * size.height);

    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    cacheBitmap = malloc( bitmapByteCount );
    if (cacheBitmap == NULL){
        return NO;
    }

    CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipFirst;

    cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), bitmapInfo);
    CGContextSetRGBFillColor(cacheContext, 0, 0, 0, 0);
    CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});
    return YES;
}

1 个答案:

答案 0 :(得分:1)

我使用此代码完全按照您的要求进行操作。我已经将颜色设置为红色,使用50%alpha而不是0%,这样您就可以看到alpha通道在那里。

@implementation ViewController
{
    CGContextRef                    cacheContext;
    void*                           cacheBitmap;
    __weak IBOutlet UIImageView*    _imageView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self setupContext:self.view.bounds.size];

    CGImageRef      cgImage = CGBitmapContextCreateImage(cacheContext);
    _imageView.image = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
}


// Name changed to avoid using the magic word "init"
- (BOOL) setupContext:(CGSize)size
{
    int bitmapByteCount;
    int bitmapBytesPerRow;

    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow = (size.width * 4);
    bitmapByteCount = (bitmapBytesPerRow * size.height);

    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    cacheBitmap = malloc( bitmapByteCount );
    if (cacheBitmap == NULL){
        return NO;
    }

    CGBitmapInfo    bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault;

    // Create and define the color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, colorSpace, bitmapInfo);
    CGContextSetRGBFillColor(cacheContext, 1., 0, 0, 0.5);
    CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});

    // Release the color space so memory doesn't leak
    CGColorSpaceRelease(colorSpace);

    return YES;
}

@end