o0oKodako0o
o0oKodako0o

Reputation: 177

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!

Upvotes: 2

Views: 2779

Answers (2)

junaidsidhu
junaidsidhu

Reputation: 3580

Try This

#pragma mark - Marge two Images 

- (UIImage *) addImageToImage:(UIImage *)img withImage2:(UIImage *)img2{

    CGSize size = CGSizeMake(imageView.image.size.width, imageView.image.size.height);
    UIGraphicsBeginImageContext(size);

    CGPoint pointImg1 = CGPointMake(0,0);
    [img drawAtPoint:pointImg1]; 

    CGPoint pointImg2 = CGPointMake(0,0);
    [img2 drawAtPoint: pointImg2];

    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}


[self addImageToImage:imageView.image withImage2:imageView2.image];

Upvotes: 2

Kris Gellci
Kris Gellci

Reputation: 9687

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();

Upvotes: 6

Related Questions