Reputation: 283
I have two PNG images with transparent background. I need to merge them to one image without losing transparent background.
I used this code
UIGraphicsBeginImageContext(firstImage.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, firstImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGRect rect = CGRectMake(0, 0, firstImage.size.width,firstImage.size.height);
// draw white background to preserve color of transparent pixels
CGContextSetBlendMode(context, kCGBlendModeDarken);
[[UIColor whiteColor] setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
CGContextRestoreGState(context);
// draw original image
CGContextSetBlendMode(context, kCGBlendModeDarken);
CGContextDrawImage(context, rect, firstImage.CGImage);
// tint image (loosing alpha) - the luminosity of the original image is preserved
CGContextSetBlendMode(context, kCGBlendModeDarken);
//CGContextSetAlpha(context, .85);
[[UIColor colorWithPatternImage:secondImage] setFill];
CGContextFillRect(context, rect);
CGContextSaveGState(context);
CGContextRestoreGState(context);
// mask by alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawImage(context, rect, firstImage.CGImage);
// image drawing code here
CGContextRestoreGState(context);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
but it return one image with white background.
Any idea why, please?
Upvotes: 0
Views: 700
Reputation: 80801
If both of your images have transparency, then drawing them both with the normal blend-mode won't in any way 'lose' the transparency.
You should just be able to draw one on top of the other:
UIGraphicsBeginImageContext(firstImage.size); // Assumes the first image is the same size as the second image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, firstImage.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, rect, firstImage.CGImage);
CGContextDrawImage(context, rect, secondImage.CGImage);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
You also don't need to save and restore the graphics state of the context (at least outside of all the drawing), unless you are going to reuse the context.
Upvotes: 2
Reputation: 188
I didn't understand very well the problem but let's try...
Try to set the view where the images will be with setOpaque like the example bellow...
[self.thatView setOpaque:NO]
Hope that helps.
Upvotes: 0