Changing UIImage color

前端 未结 13 1502
我寻月下人不归
我寻月下人不归 2020-11-28 19:28

I\'m trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(         


        
13条回答
  •  余生分开走
    2020-11-28 19:55

    This is pretty much the answer above, but slightly shortened. This only takes the image as a mask and does not actually "multiply" or color the image.

    Objective C:

        UIColor *color = <# UIColor #>;
        UIImage *image = <# UIImage #>;// Image to mask with
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [color setFill];
        CGContextTranslateCTM(context, 0, image.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextClipToMask(context, CGRectMake(0, 0, image.size.width, image.size.height), [image CGImage]);
        CGContextFillRect(context, CGRectMake(0, 0, image.size.width, image.size.height));
    
        UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    

    Swift:

        let color: UIColor = <# UIColor #>
        let image: UIImage = <# UIImage #> // Image to mask with
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        let context = UIGraphicsGetCurrentContext()
        color.setFill()
        context?.translateBy(x: 0, y: image.size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.clip(to: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), mask: image.cgImage!)
        context?.fill(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        let coloredImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    

提交回复
热议问题