How to merge two UIImages while keeping the aspect ratio and size?
ios, merge, swift, uiimage
Solution
You have two bugs in your code:
You should also calculate aspect for document image to fit it into `UIImageView`. In `mergeImages()` replace:
img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
with:
img.draw(in: getAspectFitFrame(sizeImgView: size, sizeImage: img.size))
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
}
Problem
The code is added to Github to let you understand the real problem. This is the hierarchy: ``` -- 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)] ``` I am trying to merge A with B but the result is stretched. This is the merge code: ``` 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 } ``` Note: - .contentMode = .scaleAspectFit - Code works but the result is stretched. - See this line in code, `let size = self.imgBackground.frame.size` – I need to change this to fix the problem. Find the origin of subview with respect to UIImage size Here's the screenshot to understand the problem: What should I do to get the proper output of merge function?