如何在 Swift 中将两个 UIImage 组合成一个图像?

How to combine two UIImages into a single Image in Swift?

我一直在尝试合并两张图片,一张在上面,另一张在下面。下面这段代码似乎不起作用。 x 协调器是正确的,但 y 似乎不正确,当我更改它时它会裁剪顶部图像。我做错了什么?

func combine(bottomImage: Data, topImage: Data) -> UIImage {
    let bottomImage = UIImage(data: topImage)
    let topImage = UIImage(data: bottomImage)
    let size = CGSize(width: bottomImage!.size.width, height: bottomImage!.size.height + topImage!.size.height)
    UIGraphicsBeginImageContext(size)
    let areaSizeb = CGRect(x: 0, y: 0, width: bottomImage!.size.width, height: bottomImage!.size.height)
    let areaSize = CGRect(x: 0, y: 0, width: topImage!.size.width, height: topImage!.size.height)
    bottomImage!.draw(in: areaSizeb)
    topImage!.draw(in: areaSize)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}

您正在将两个图像绘制到同一个矩形中。您也不应该使用强制展开。如果出现任何问题,这会导致您的应用程序崩溃。

还有其他各种小错误。

像这样更改您的函数:

// Return an Optional so we can return nil if something goes wrong
func combine(bottomImage: Data, topImage: Data) -> UIImage? {

    // Use a guard statement to make sure 
    // the data can be converted to images
    guard 
      let bottomImage = UIImage(data: bottomImage),
      let topImage = UIImage(data: topImage) else {
        return nil
    }
    // Use a width wide enough for the widest image
    let width = max(bottomImage.size.width, topImage.size.width)

    // Make the height tall enough to stack the images on top of each other.
    let size = CGSize(width: width, height: bottomImage.size.height + topImage.size.height)
    UIGraphicsBeginImageContext(size)
    let bottomRect = CGRect(
      x: 0, 
      y: 0, 
      width: bottomImage.size.width, 
      height: bottomImage.size.height)

    // Position the bottom image under the top image.
    let topRect = CGRect(
      x: 0, 
      y: bottomImage.size.height, 
      width: topImage.size.width, 
      height: topImage.size.height)
        
    bottomImage.draw(in: bottomRect)

    topImage!.draw(in: topRect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

(你真的应该使用 UIGraphicsImageRenderer 而不是调用 UIGraphicsBeginImageContext()/ UIGraphicsEndImageContext()。)

编辑:

请注意,如果两张图片的宽度不同,上述代码会在较窄的图片右侧留下“死角 space”。您还可以使代码居中显示较窄的图像,或将其放大为相同的宽度。 (如果你真的放大它,我建议在两个维度上放大它以保持原始的纵横比。否则它看起来会被拉伸和不自然。)