UIImage+grayColor.h
#import <UIKit/UIKit.h>
@interface UIImage (grayColor)
+ (UIImage *)grayImage:(UIImage *)sourceImage;
@end
UIImage+grayColor.m
#import "UIImage+grayColor.h"
@implementation UIImage (grayColor)
+ (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;
}
@end
// 使用
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
[imageView setImage:[UIImage grayImage:[UIImage imageNamed:@"dark.jpg"]]];
[self.view addSubview:imageView];