首页 > 解决方案 > 合并两个 UIImages swift 4

问题描述

我有一个从设备的相机捕获的图像,我想在上面添加一个UITextView然后将它保存到图库中。我正在使用以下代码从文本视图中获取图像

extension UITextView {
    var imageOfView: UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }
}

然后,通过使用以下代码,我尝试将上面的图像添加到拍摄的图像中:

extension UIImage {

    func combine(with image: UIImage, at point: CGPoint, isLandscapeMode: Bool = false) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)

        self.draw(at: .zero)
        image.draw(at: point)

        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return result!
    }
}

最后,我调用这里的方法将编辑后的图像发送到上一页:

onImageEdited?(capturedImage.combine(with: textArea.imageOfView, at: textArea.frame.origin, isLandscapeMode: true))

查看下面的屏幕截图,可以看到大小发生了变化,并且位置似乎是随机选择的。知道为什么以及如何解决这个问题吗?

编辑过程中:

保存更改之前

保存后:

保存更改后

PS:截图和编辑页面为横屏模式

标签: iosswiftbitmapuiimage

解决方案


在 Swift 4.2 中尝试此代码

func stitchImages(images: [UIImage], isVertical: Bool) -> UIImage {
    var stitchedImages : UIImage!
    if images.count > 0 {
        var maxWidth = CGFloat(0), maxHeight = CGFloat(0)
        for image in images {
            if image.size.width > maxWidth {
                maxWidth = image.size.width
            }
            if image.size.height > maxHeight {
                maxHeight = image.size.height
            }
        }
        var totalSize : CGSize
        let maxSize = CGSize(width: maxWidth, height: maxHeight)
        if isVertical {
            totalSize = CGSize(width: maxSize.width, height: maxSize.height * (CGFloat)(images.count))
        } else {
            totalSize = CGSize(width: maxSize.width  * (CGFloat)(images.count), height:  maxSize.height)
        }
        UIGraphicsBeginImageContext(totalSize)
        for image in images {
            let offset = (CGFloat)(images.index(of: image)!)
            let rect =  AVMakeRect(aspectRatio: image.size, insideRect: isVertical ?
                CGRect(x: 0, y: maxSize.height * offset, width: maxSize.width, height: maxSize.height) :
                CGRect(x: maxSize.width * offset, y: 0, width: maxSize.width, height: maxSize.height))
            image.draw(in: rect)
        }
        stitchedImages = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }
    return stitchedImages
  }
}

你可以使用这个:

@IBOutlet weak var imageView: UIImageView!
let imageArray = [image1, image3, image4, image4]

override func viewDidLoad() {
    super.viewDidLoad()
    let image = stitchImages(images: imageArray, isVertical: false)
    imageView.image = image
}

推荐阅读