iPhone, how does one overlay one image onto another to create a new image to save? (watermark)

SolidSnake4444 picture SolidSnake4444 · Aug 11, 2011 · Viewed 30.8k times · Source

Basically I want to take an image that the user chooses from their photo library and then apply a watermark, a triangle in the lower right that has the app name on it. I have the second image already made with a transparent layer in photoshop.

I tried a function, which I can't remember the exact name, but it involved CGIImages and masks. This combines the two images, but as a mask, which made the image darker where the transparent layer was and the images were not merged per se, just masked.

How would I get the watermark image to merge with another image, to make a UIImage, without displaying the images on the screen?

Thank you.

Answer

omz picture omz · Aug 11, 2011

It's pretty easy:

UIImage *backgroundImage = [UIImage imageNamed:@"image.png"];
UIImage *watermarkImage = [UIImage imageNamed:@"watermark.png"];

UIGraphicsBeginImageContext(backgroundImage.size);
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
[watermarkImage drawInRect:CGRectMake(backgroundImage.size.width - watermarkImage.size.width, backgroundImage.size.height - watermarkImage.size.height, watermarkImage.size.width, watermarkImage.size.height)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

If you want the background and watermark to be of the same size then use this code

...
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
[watermarkImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
...