我正在尝试使一些像素透明,然后在某个阶段恢复其透明度。
首先,我需要使图像完全透明,然后将其从透明图像恢复为正常,因此我从头开始进行开发,使图像变为透明(Alpha = 0),然后将其透明度恢复为正常( Alpha = 255)。
+ (UIImage *)getOpaqueImageFrom:(UIImage *)image {
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
NSUInteger bitmapByteCount = bytesPerRow * height;
unsigned char *rawData = (unsigned char*) calloc(bitmapByteCount, sizeof(unsigned char));
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
int byteIndex = 0;
while (byteIndex < bitmapByteCount) {
unsigned char red = rawData[byteIndex];
unsigned char green = rawData[byteIndex + 1];
unsigned char blue = rawData[byteIndex + 2];
unsigned char alpha = rawData[byteIndex + 3];
rawData[byteIndex + 3] = 255;
byteIndex += 4;
}
CGImageRef imgref = CGBitmapContextCreateImage(context);
UIImage *result = [UIImage imageWithCGImage:imgref];
CGImageRelease(imgref);
CGContextRelease(context);
free(rawData);
return result;
}
因此,在getOpaqueImageFrom中,我将以RGBA格式发送图像(完全透明的图像)。 假设
.... [255, 255, 255, 0] ....
.... [255, 255, 255, 0] ....
.... [255, 255, 255, 0] ....
但是结果是,我只会得到一张黑色图像
.... [0, 0, 0, 255] ....
.... [0, 0, 0, 255] ....
.... [0, 0, 0, 255] ....
因为kCGImageAlphaPremultipliedFirst(因为它已预乘RGBA)。
嗯,所以我应该使用非预乘位图标志来获取源(而不是预乘)RGB值,对吧?
kCGImageAlphaNone, /* For example, RGB. */
kCGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */
kCGImageAlphaPremultipliedFirst, /* For example, premultiplied ARGB */
kCGImageAlphaLast, /* For example, non-premultiplied RGBA */
kCGImageAlphaFirst, /* For example, non-premultiplied ARGB */
kCGImageAlphaNoneSkipLast, /* For example, RBGX. */
kCGImageAlphaNoneSkipFirst, /* For example, XRGB. */
kCGImageAlphaOnly /* No color data, alpha data only */
我选择了kCGImageAlphaLast,但是according to Apple's Core Graphics documentation kCGImageAlphaLast 目前在iOS上不受支持,仅保留了kCGImageAlphaPremultipliedFirst或kCGImageAlphaPremultipliedLast作为替代。
所以我只想找到一种将透明图像返回的方法。 或者我只需要可以在iOS 11以上版本中使用的kCGImageAlphaLast替代方案
语言并不重要,因为我可以在项目内部使用swift / obj-c / c ++或OpenCV。