Search code examples
iosgraphicscgaffinetransform

How can I merge 2 image in 2 UIImageView into 1 image


I want to merge 2 image in 2 UIImageView into 1 image with "correct" position, angle, ratio scale as I see on screen.

In my project, there are 2 UIImageView - imageView is the main UIImageView - topImageView is the overlay UIImageView that can be drag, rotate, scale

I can save image merged by draw 2 images but wrong position, angle, ratio scale.

This is my code:

UIImage *img = topImageView.image;
UIImage *bottomImg = self.imageView.image;
CGSize bounds = self.imageView.image.size;

UIGraphicsBeginImageContext(bounds);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, topImageView.image.size.width * 0.5, topImageView.image.size.height * 0.5);
CGFloat angle = atan2(topImageView.transform.b, topImageView.transform.a);
CGContextRotateCTM(ctx, angle);

[topImageView.image drawInRect:CGRectMake(-topImageView.image.size.width * 0.5,
                                          -topImageView.image.size.height * 0.5,
                                          topImageView.image.size.width,
                                          topImageView.image.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIGraphicsBeginImageContext(bounds);
[bottomImg drawInRect:CGRectMake(0, 0, bounds.width, bounds.height)];
[newImage drawInRect:CGRectMake(topImageView.frame.origin.x,
                                topImageView.frame.origin.y,
                                newImage.size.width,
                                newImage.size.height)];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Any idea to help me? Thanks a lot!


Solution

  • Add both of those images as subviews to a UIView. Do what you need to the images and then take a snapshot of the UIVIew like so:

    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *MergedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();