ios 如何在Swift中创建由两个图像组成的合成图像?

q43xntqr  于 2023-07-01  发布在  iOS
关注(0)|答案(2)|浏览(154)

我想创建一个新的UIImage,它是一个UIImage叠加在另一个之上的合成。我如何才能做到这一点?

q0qdq0h2

q0qdq0h21#

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

o7jaxewo2#

下面是一个可以与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
}

相关问题