- (void)viewDidLoad {
[superviewDidLoad];
NSString *_imageURL =@"https://developers.google.cn/web/images/hero-2x.png";
self.backImage = [[UIImageViewalloc]initWithFrame:CGRectMake(10,100, 200, 200)];
self.backImage.backgroundColor = [UIColor redColor];
self.backImage.clipsToBounds = YES;
[self.viewaddSubview:self.backImage];
BOOL isSoldOut =YES;
[[SDWebImageDownloadersharedDownloader] downloadImageWithURL:[NSURLURLWithString:_imageURL]options:SDWebImageDownloaderUseNSURLCacheprogress:^(NSInteger receivedSize,NSInteger expectedSize) {
} completed:^(UIImage *image,NSData *data, NSError *error,BOOL finished) {
self.backImage.image = isSoldOut ? [selfgrayImage:image]:image;
self.backImage.contentMode = UIViewContentModeScaleAspectFill;
}];
}
-(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) {
returnnil;
}
CGContextDrawImage(context,
CGRectMake(0,0, width, height), sourceImage.CGImage);
UIImage *grayImage = [UIImageimageWithCGImage:CGBitmapContextCreateImage(context)];
CGContextRelease(context);
return grayImage;
}
以下为原图和去色后的图片: