iOS:创建一个更暗的UIImage版本并保持透明像素不变? [英] iOS: create an darker version of UIImage and leave transparent pixels unchanged?

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

问题描述

我找到了



通过向现有UIImage添加阴影来创建新的UIImage





UIImage,有一个简单的方法吗?使它变暗或全黑的方法



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



<我有一个UIImage,它可能有一些透明像素,我需要创建一个新的UIImage,其中非透明像素变暗,有什么办法可以做到这一点吗?我正在考虑使用UIBezierPath,但我不知道如何只为非透明像素做这件事。

解决方案

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

  +(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版本并保持透明像素不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆