如何在保持纵横比和大小的同时合并两个UIImages?

Hem*_*ang 5 merge uiimage ios swift

代码被添加到Github,让您了解真正的问题.


这是层次结构:

-- ViewController.View P [width: 375, height: 667]
---- UIImageView A       [width: 375, height: 667] Name: imgBackground
                         [A is holding an image of size(1287,1662)]
---- UIImageView B       [width: 100, height: 100] Name: imgForeground
                         [B is holding an image of size(2400,982)]
Run Code Online (Sandbox Code Playgroud)

我试图将A与B合并,但结果已经拉长.

这是合并代码:

func mixImagesWith(frontImage:UIImage?, backgroundImage: UIImage?, atPoint point:CGPoint, ofSize signatureSize:CGSize) -> UIImage {
    let size = self.imgBackground.frame.size
    UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
    backgroundImage?.draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
    frontImage?.draw(in: CGRect.init(x: point.x, y: point.y, width: signatureSize.width, height: signatureSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)

注意:

以下是了解问题的屏幕截图:

在此输入图像描述

我该怎么做才能获得合适函数的正确输出?

mix*_*xel 2

您的代码中有两个错误:

  1. 您还应该计算文档图像的长宽比以使其适合UIImageView. 替换mergeImages():

    img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    
    Run Code Online (Sandbox Code Playgroud)

    和:

    img.draw(in: getAspectFitFrame(sizeImgView: size, sizeImage: img.size))
    
    Run Code Online (Sandbox Code Playgroud)
  2. When calculating aspect you center image horizontally/vertically if its width/height less then UIImageView width/height. But instead of comparing newWidth and newHeight you should compare factors:

    if hfactor > vfactor {
        y = (sizeImgView.height - newHeight) / 2
    } else {
        x = (sizeImgView.width - newWidth) / 2
    }
    
    Run Code Online (Sandbox Code Playgroud)