改变图片颜色(灰色显示)

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];

 

posted @ 2014-02-08 10:07  菜鸟程序猿  阅读(638)  评论(0编辑  收藏  举报