给定一个 CGRect ( rect
) 和一个 UIImage ( image
),如何获得矩形中图像像素的 alpha 值(仅)?
以下代码始终返回 0 alpha,无论是图像还是矩形。
CGContextRef context = CGBitmapContextCreate(NULL,
rect.size.width,
rect.size.height,
8,
rect.size.width,
NULL,
kCGImageAlphaOnly);
UIGraphicsPushContext(context);
[image drawInRect:rect];
char *pixels = CGBitmapContextGetData(context);
NSUInteger pixelCount = rect.size.width * rect.size.height;
for (int i = 0; i < pixelCount; i++)
{
char pixel = pixels[i];
CGFloat alpha = pixel / 255.0;
NSLog(@"%f", alpha);
}
UIGraphicsPopContext();
CGContextRelease(context);