本文介绍了iOS:创建一个更暗的UIImage版本并保持透明像素不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了









但所选答案对我不起作用。



解决方案

这是即使它们是透明的,我用它来着色图像。

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

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

[颜色设置];
CGContextFillRect(context,area);

CGContextRestoreGState(context);

CGContextSetBlendMode(context,kCGBlendModeMultiply);

CGContextDrawImage(context,area,image.CGImage);

UIImage * colorizedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

返回colorizedImage;
}

要使图像变暗,您将通过该方法将黑色或灰色UIColor降低透明度。


I found

Create new UIImage by adding shadow to existing UIImage

and

UIImage, is there an easy way to make it darker or all black

But the selected answers do not work for me.

I have an UIImage, which may have some transparent pixels in it, I need to create a new UIImage with non-transparent pixels darkened, is there any way to do this? I was thinking of using UIBezierPath but I don't know how to do it for only non-transparent pixels.

解决方案

This is the class I use to color images even if they are transparent.

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

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

To darken the image you would pass the method a black or gray UIColor with lowered transparency.

这篇关于iOS:创建一个更暗的UIImage版本并保持透明像素不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 08:28