CoreGraphics的功能非常强大,可以绘制出各种图形,其中,强大的核心动画 Core Animation 都是基于 CoreGraphics 实现的;
利用 CoreGraphics 将彩色图片转灰白图片事例
原始图片
转化为灰色图片
核心代码
/**
* 普通图片转位灰白图片
*
* @param image 普通图片
*
* @return 灰白图片
*/
- (UIImage *)grayImage:(UIImage *)image{
int width = image.size.width;
int height = image.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(nil,
width,
height,
8,
0,
colorSpace,
kCGBitmapByteOrderDefault);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return nil;
}
CGContextDrawImage(context,
CGRectMake(0, 0, width, height), image.CGImage);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *grayImage = [UIImage imageWithCGImage:imageRef];
CFRelease(imageRef);
CGContextRelease(context);
return grayImage;
}
方法的调用和显示图片
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:iamgeName];
#pragma mark ----------------------------------------
UIImage *grayImage = [self grayImage:image];
#pragma mark ----------------------------------------
UIImageView *imageView = [[UIImageView alloc] initWithImage:grayImage];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.frame = self.view.bounds;
[self.view addSubview:imageView];
}