Merge two pictures
Sometimes you might need to merge two pictures into one to show on your iPhone or iPad app. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to resize any given image.
Strategy to merge two pictures is fairly simple: First, we need to determine what final destination the picture you want to merge will be. Second, we need to create a rectangle for that size. Third, create an empty image object based on your new size. Fourth, superimpose your existing images onto your new image object.
Here are actual code samples:
The first thing you need to do is to set the size of the new image, to do so, use the following line:
UIGraphicsBeginImageContext ( SOME_WIDTH, SOME_HEIGHT )
Then you add the first and second pictures giving them starting x and y coordinates and width and height.
[YOUR_PICTURE_ONE_PTR drawInRect:CGRectMake( START_X, START_Y, SOME_WIDTH, SOME_HEIGHT)]; [YOUR_PICTURE_TWO_PTR drawInRect:CGRectMake( START_X, START_Y, SOME_WIDTH, SOME_HEIGHT)];
Then you will need to set a new image to an UIImage object
UIImage *NEW_DESTINATION_IMAGE = UIGraphicsGetImageFromCurrentImageContext();
Finally,
UIGraphicsEndImageContext()
So, this is how a final code for merging two pictures will look like:
1 - (UIImage )mergeImage:(UIImage )pic1 : (UIImage *) pic2 2 { 3 // both images are the same size so we can use the width of any image 4 float width = pic1.size.width; 5 // both images are the same size so we can double the height of any image 6 float height = pic1.size.height * 2 ; 7 UIGraphicsBeginImageContext(width, height); 8 9 [pic1 drawInRect:CGRectMake(0, 0, pic1.size.width, pic1.size.height)]; 10 // note the starting Y coordinate is the height of pic1 11 [pic2 drawInRect:CGRectMake(0, pic1.size.height, pic2.size.width, pic2.size.height)]; 12 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 13 UIGraphicsEndImageContext(); 14 return newImage; 15 }