How to combine/ merge 2 images into 1

后端 未结 8 1018
粉色の甜心
粉色の甜心 2020-12-07 12:32

I would like to know what to do to save 2 images into 1 image.

One of the photos can be moved, rotated and zoomed in/out...

I\'m doing this, but it basically

相关标签:
8条回答
  • 2020-12-07 13:11

    You can create graphics context and draw both images in it. You'll get an image result from both your source images combined.

    - (UIImage*)imageByCombiningImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
        UIImage *image = nil;
    
        CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width), MAX(firstImage.size.height, secondImage.size.height));
        if (UIGraphicsBeginImageContextWithOptions != NULL) {
            UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
        } else {
            UIGraphicsBeginImageContext(newImageSize); 
        }
        [firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2), 
                                            roundf((newImageSize.height-firstImage.size.height)/2))]; 
        [secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2), 
                                             roundf((newImageSize.height-secondImage.size.height)/2))]; 
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    
    0 讨论(0)
  • 2020-12-07 13:11

    Swift 3

    In this example the frontImage is being drawn inside the other image using a insetBy of 20% margin.

    The background image must be drawn before and then the front image in sequence.

    I used this to place a "Play" icon image in front a video frame image inside a UIImageView like below:

    Usage:

    self.image = self.mergedImageWith(frontImage: UIImage.init(named: "play.png"), backgroundImage: UIImage.init(named: "backgroundImage.png")))
    

    Method:

    func mergedImageWith(frontImage:UIImage?, backgroundImage: UIImage?) -> UIImage{
    
        if (backgroundImage == nil) {
            return frontImage!
        }
    
        let size = self.frame.size
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    
        backgroundImage?.draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
        frontImage?.draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height).insetBy(dx: size.width * 0.2, dy: size.height * 0.2))
    
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
    
        return newImage
    }
    
    0 讨论(0)
提交回复
热议问题