如何在Swift中将两个UIImage合并为一个映像?

如何在Swift中将两个UIImage合并为一个映像?,swift,uiimage,Swift,Uiimage,我一直在尝试合并两个图像,其中一个在顶部,另一个在底部。下面的代码似乎不起作用。x坐标是正确的,但y看起来不正确,当我修改它时,它会裁剪顶部图像。我做错了什么 func combine(bottomImage: Data, topImage: Data) -> UIImage { let bottomImage = UIImage(data: topImage) let topImage = UIImage(data: bottomImage) let size =

我一直在尝试合并两个图像,其中一个在顶部,另一个在底部。下面的代码似乎不起作用。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
}
(您应该真正使用UIGraphicsImageEnder,而不是调用
UIGraphicsBeginImageContext()
/
UIGraphicsSendImageContext()

编辑:
请注意,如果两幅图像的宽度不同,则上述代码将在较窄图像的右侧留下“死区”。您还可以将代码中心设置为更窄的图像,或者将其放大到相同的宽度。(如果你确实放大它,我建议在两个维度上都放大它以保持原始的纵横比。否则它看起来会拉伸和不自然。)

这看起来不是快速UI——你是说UIKit吗?这个问题中的快速UI在哪里?“y看起来不对”不是。底部图像y必须是顶部图像高度。而且这些不是尺寸,它们是矩形的。非常感谢邓肯,它成功了!如果我的答案解决了你的问题,你应该点击复选标记接受它。这是一个非常强大的规范在这个网站上。一旦你有了足够的声誉,向上投票特别有用的答案也是一种很好的形式,尽管是可选的。而且你的问题似乎是关于纯粹的Swift,而不是SwiftUI。您应该编辑您的问题,将标题和关键字更改为Swift,或者添加相关的SwiftUI代码,以便该问题实际上具有SwiftUI组件。