我目前正在尝试获取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зҡ„еқҗж Үи®Ўз®—з»ҷе®ҡОұйҖҡйҒ“зҡ„ж•°з»„зҙўеј•гҖӮ
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);