我目前正在尝试获取 UIImageView 中像素的 alpha 值。我从 [UIImageView image] 获得了 CGImage 并由此创建了一个 RGBA 字节数组。Alpha 是预乘的。
CGImageRef image = uiImage.CGImage;
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
rawData = malloc(height * width * 4);
bytesPerPixel = 4;
bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(
rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big
);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
CGContextRelease(context);
然后,我使用 UIImageView 中的坐标计算给定 alpha 通道的数组索引。
int byteIndex = (bytesPerRow * uiViewPoint.y) + uiViewPoint.x * bytesPerPixel;
unsigned char alpha = rawData[byteIndex + 3];
但是我没有得到我期望的值。对于图像的完全黑色透明区域,我得到 alpha 通道的非零值。我是否需要转换 UIKit 和 Core Graphics 之间的坐标 - 即:y 轴是否倒置?还是我误解了预乘的 alpha 值?
更新:
@Nikolai Ruhe 的建议是关键。我实际上不需要在 UIKit 坐标和 Core Graphics 坐标之间进行转换。但是,在设置混合模式后,我的 alpha 值符合我的预期:
CGContextSetBlendMode(context, kCGBlendModeCopy);