iOS: create an darker version of UIImage and leave transparent pixels unchanged?

前端 未结 4 546
小蘑菇
小蘑菇 2021-02-05 16:31

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

4条回答
  •  忘掉有多难
    2021-02-05 17:24

    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.

提交回复
热议问题