Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Objective C: Merge two images

+ (UIImage*)mergeImage:(UIImage*)first withImage:(UIImage*)second
{
 // get size of the first image
 CGImageRef firstImageRef = first.CGImage;
 CGFloat firstWidth = CGImageGetWidth(firstImageRef);
 CGFloat firstHeight = CGImageGetHeight(firstImageRef);
 
 // get size of the second image
 CGImageRef secondImageRef = second.CGImage;
 CGFloat secondWidth = CGImageGetWidth(secondImageRef);
 CGFloat secondHeight = CGImageGetHeight(secondImageRef);
 
 // build merged size
 CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
 
 // capture image context ref
 UIGraphicsBeginImageContext(mergedSize);
 
 //Draw images onto the context
 [first drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
 [second drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)]; 
 
 // assign context to new UIImage
 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
 
 // end context
 UIGraphicsEndImageContext();

 return newImage;
}

If you want to resize new image to new desired size use function from previous post.

Objective C: Resize image

+ (UIImage*)resizeImageWithImage:(UIImage*)image toSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
 
    // draw in new context, with the new size
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
 
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
 
    // End the context
    UIGraphicsEndImageContext();
 
    return newImage;
}