- (UIImage *)grayImage:(UIImage *)sourceImage
{
int bitmapInfo = kCGImageAlphaNone;
int width = sourceImage.size.width;
int height = sourceImage.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate (nil,
width,
height,
8, // bits per component
0,
colorSpace,
bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return nil;
}
CGContextDrawImage(context,
CGRectMake(0, 0, width, height), sourceImage.CGImage);
UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
return grayImage;
}
//CGBitmapContextCreate 在配备Retina的设备上绘制模糊的解决方法
-(UIImage *)grayImage:(UIImage *)sourceImage
{
int bitmapInfo = kCGImageAlphaNone;
int width = sourceImage.size.width;
int height = sourceImage.size.height;
CGFloat scale = [[UIScreen mainScreen] scale];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate (nil,
width * scale,
height * scale,
8, // bits per component
width * scale * 4,
colorSpace,
bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return nil;
}
CGContextDrawImage(context,
CGRectMake(0, 0, width * scale, height * scale), sourceImage.CGImage);
UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
return grayImage;
}