Skip to content

Instantly share code, notes, and snippets.

@WedgeSparda
Last active December 7, 2015 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WedgeSparda/19aa1425de0e6c56332d to your computer and use it in GitHub Desktop.
Save WedgeSparda/19aa1425de0e6c56332d to your computer and use it in GitHub Desktop.
Combine two UIImages
// Let’s say we have two images we want to combine; say an image of a person that we want to overlay an image of a funny hat on to.
// Here are the two UIImages:
UIImage *personImage = [UIImage imageNamed:@"person.jpg"];
UIImage *hatImage = [UIImage imageNamed:@"hat.png];
// In this case we want the resultant image to be that same size as the personImage.
// Let’s get the size that we want for the final image:
CGSize finalSize = [personImage size];
// Also get the size of the hat image which is probably much smaller:
CGSize hatSize = [hatImage size];
//Now we need to create a graphics context in which we will do our drawing:
UIGraphicsBeginImageContext(finalSize);
// The graphics context is kind of like out piece of paper that we will draw to.
// The first thing we want to draw on it is the photo of the person:
[personImage drawInRect:CGRectMake(0,0,finalSize.width,finalSize.height)];
// Now we draw the hat at the position that we want it to be on top of the other image.
[hatImage drawInRect:CGRectMake(HAT_X_POS,HAT_Y_POS,hatSize.width,hatSize.height)];
// Next we create the new UIImage with:
UIImage *newImage = [UIGraphicsGetImageFromCurrentImageContext();
// Finally we need to clean up and close the context as we no longer need it:
UIGraphicsEndImageContext();
// That is all there is to it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment