Merge two images by retaining opacity of Image

M

UIGraphicsBeginImageContext(topImage.size);

 

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0, topImage.size.height);

CGContextScaleCTM(context, 1.0, -1.0);

CGRect rect = CGRectMake(0, 0, topImage.size.width, topImage.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, bottomImage.CGImage);

// tint image (loosing alpha) – the luminosity of the original image is preserved

CGContextSetBlendMode(context, kCGBlendModeDarken);

[[UIColor colorWithPatternImage:topImage] setFill];

CGContextFillRect(context, rect);

// mask by alpha values of original image

CGContextSetBlendMode(context, kCGBlendModeDestinationIn);

CGContextDrawImage(context, rect, topImage.CGImage);

// image drawing code here

UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

 

About the author

yogita.balganure
By yogita.balganure

Category