获取视图快照而不应用alpha视图

时间:2014-10-31 13:53:48

标签: ios objective-c core-graphics

即使将视图的.alpha属性设置为非1值,我也会做一些要求我获取视图快照的完全不透明版本的内容。

我通过iOS 7中的快照创建快照:

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[self drawViewHierarchyInRect:CGRectMake(0, 0, size.width, size.height) afterScreenUpdates:NO];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

我正在考虑将其转换为位图数据并将所有alpha值修改为1 - view.alpha。我认为这样可行,但我需要获得非预乘的位图数据。

CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
uint32_t *bitmapData;

size_t bitsPerPixel = 32;
size_t bitsPerComponent = 8;
size_t bytesPerPixel = bitsPerPixel / bitsPerComponent;

size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);

size_t bytesPerRow = width * bytesPerPixel;
size_t bufferLength = bytesPerRow * height;

colorSpace = CGColorSpaceCreateDeviceRGB();

if(!colorSpace) {
    NSLog(@"Error allocating color space RGB\n");
    return NULL;
}

// Allocate memory for image data
bitmapData = (uint32_t *)malloc(bufferLength);

if(!bitmapData) {
    NSLog(@"Error allocating memory for bitmap\n");
    CGColorSpaceRelease(colorSpace);
    return NULL;
}

//Create bitmap context
context = CGBitmapContextCreate(bitmapData,
                                width,
                                height,
                                bitsPerComponent,
                                bytesPerRow,
                                colorSpace,
                                (kCGBitmapAlphaInfoMask & kCGImageAlphaLast)); //RGBA

除非有更简单的方法,为什么我不能让kCGImageAlphaLast工作? kCGImageAlphaPremultipliedLast似乎有效,但这不起作用。

<Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 32 bits/pixel; 3-component color space; kCGImageAlphaLast; 8192 bytes/row.

1 个答案:

答案 0 :(得分:1)

为什么不把这个视图放在containerView中?改变容器的alpha,然后保留这个“图像生成视图”,其alpha值为1.0 ....你的UI保持不变,你得到了你的图像......