3

I want to create a new UIImage that is a composite of one UIImage overlaid on top of another. How can I achieve this?

2 Answers 2

6
//
// Return composite image of image2 overlayed on image1
//
func compositeImage(image1: UIImage, image2: UIImage) -> UIImage {
    var bounds1 = CGRectMake(0, 0, image1.size.width, image1.size.height)
    var bounds2 = CGRectMake(0, 0, image2.size.width, image2.size.height)
    var colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    var ctx = CGBitmapContextCreate(nil,
        CGImageGetWidth(image1.CGImage),
        CGImageGetHeight(image1.CGImage),
        CGImageGetBitsPerComponent(image1.CGImage),
        CGImageGetBytesPerRow(image1.CGImage),
        CGImageGetColorSpace(image1.CGImage),
        bitmapInfo)!
    CGContextDrawImage(ctx, bounds1, image1.CGImage)
    CGContextSetBlendMode(ctx, kCGBlendModeNormal) // one image over the other
    CGContextDrawImage(ctx, bounds2, image2.CGImage)
    return UIImage(CGImage: CGBitmapContextCreateImage(ctx))!
}
Sign up to request clarification or add additional context in comments.

1 Comment

How can I modify the above, if I'd want the images to be side-by-side, rather than as an overlay?
3

Here's a version that will work with Swift 4:

/**
 Composite two or more image on top of one another to create a single image.
 This function assumes all images are same size.

 - Parameters:
 - images: An array of UIImages

 - returns: A compsite image composed of the array of images passed in
 */
func compositeImages(images: [UIImage]) -> UIImage {
    var compositeImage: UIImage!
    if images.count > 0 {
        // Get the size of the first image.  This function assume all images are same size
        let size: CGSize = CGSize(width: images[0].size.width, height: images[0].size.height)
        UIGraphicsBeginImageContext(size)
        for image in images {
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            image.draw(in: rect)
        }
        compositeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }
    return compositeImage
}

1 Comment

This answer is better than my answer IMO, so I'm making it the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.