我有一个带有一些alpha值的UIImage,想要制作一个灰色版本。我一直在使用下面的,它适用于图像的非alpha部分,但是由于alpha不支持/关闭alpha部分变黑...我将如何成功转换alpha支持?
(我在stackoverflow周围的代码中进行了修改,以支持其他尺度(读取视网膜))
-(UIImage*)grayscaledVersion2 {
// Create image rectangle with current image width/height
const CGRect RECT = CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale);
// Grayscale color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// Create bitmap content with current image size and grayscale colorspace
CGContextRef context = CGBitmapContextCreate(nil, RECT.size.width, RECT.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
// kCGImageAlphaNone = no alpha, kCGImageAlphaPremultipliedFirst/kCGImageAlphaFirst/kCGImageAlphaLast = crash
// Draw image into current context, with specified rectangle
// using previously defined context (with grayscale colorspace)
CGContextDrawImage(context, RECT, [self CGImage]);
// Create bitmap image info from pixel data in current context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage* imageGray = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
DLog(@"greyed %@ (%f, %f %f) into %@ (%f, %f %f)", self, self.scale, self.size.width, self.size.height, imageGray, imageGray.scale, imageGray.size.width, imageGray.size.height);
// Release colorspace, context and bitmap information
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
CFRelease(imageRef);
return imageGray;
}