Search code examples
iosobjective-cipad

How to merge transparent PNG Image with color


I tried with drawInRect and CGContextDrawImage but it is applying to the whole image.

I want it to apply to the image part only, not to the transparent part. Does anyone know how to do it?


Solution

  • Thanks for the help...i tried this code it worked for me finally.

    UIGraphicsBeginImageContext(firstImage.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, firstImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGRect rect = CGRectMake(0, 0, firstImage.size.width, firstImage.size.height);
    // draw black background to preserve color of transparent pixels
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    [[UIColor whiteColor] setFill];
    CGContextFillRect(context, rect);
    // draw original image
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextDrawImage(context, rect, firstImage.CGImage);
    // tint image (loosing alpha) - the luminosity of the original image is preserved
    CGContextSetBlendMode(context, kCGBlendModeDarken);
    [[UIColor colorWithPatternImage:secondImage] setFill];
    CGContextFillRect(context, rect);
    // mask by alpha values of original image
    CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
    CGContextDrawImage(context, rect, firstImage.CGImage);
    //[firstImage drawInRect:rect];
    
    // image drawing code here
    UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();