如何在Swift中制作由两个图像组成的合成图像?

时间:2015-03-23 05:12:51

标签: ios swift uiimage

我想创建一个新的UIImage,它是一个叠加在另一个上面的UIImage的复合体。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:5)

//
// 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))!
}

答案 1 :(得分:1)

这是一个适用于Swift 4的版本:

/**
 Composite two or more image on top of one another to create a single image.
 This function assume 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
}