UIImage添加灰色透明度

时间:2014-09-09 00:15:36

标签: ios objective-c uiimage

我想做以下事情:

enter image description here

正如您所看到的,一张图片(已选中)没有灰色渐变而另一张图像(未选择的项目)

我尝试了多种解决方案。包括用灰色着色图像

    - (UIImage *)colorizeImage:(UIImage *)image withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(image.size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);

    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -area.size.height);

    CGContextSaveGState(context);
    CGContextClipToMask(context, area, image.CGImage);

    [color set];
    CGContextFillRect(context, area);

    CGContextRestoreGState(context);

    CGContextSetBlendMode(context, kCGBlendModeMultiply);

    CGContextDrawImage(context, area, image.CGImage);

    UIImage *colorizedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return colorizedImage;
}

然而,通过这种方法,我遇到了一个问题,即如果图像的bg具有透明度,则它下面的白色会透过它看起来很奇怪:

enter image description here

如何检测透明度并将透明度更改为白色?或者有更好的解决方案吗?

image = [self imageWithImage:image scaledToSize:CGSizeMake((self.collectionViewContainer.frame.size.width/3),90)];
UIImage *unSelected = [self colorizeImage:image withColor:[[UIColor grayColor] colorWithAlphaComponent:.9]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:unSelected highlightedImage:image];

1 个答案:

答案 0 :(得分:0)

由于您只想对图像应用灰色色调,请尝试这种方式:

- (UIImage *)colorizeImage:(UIImage *)image withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(image.size, NO, image.scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);

    [image drawInRect:area];

    [color set];
    CGContextFillRect(context, area);

    UIImage *colorizedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return colorizedImage;
}

这会绘制图像,然后在图像上绘制颜色。假设颜色部分透明,则整个新图像将被着色。

正如您最初所做的那样,由于图像剪裁,您只对非透明部分着色。

此更新还会对新图像应用适当的比例以匹配原始图像。

相关问题