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

 

相关文章:

  • 2022-12-23
  • 2021-12-18
  • 2021-10-23
  • 2022-12-23
  • 2021-05-11
  • 2021-06-21
  • 2021-08-16
  • 2022-02-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案