I made static utility functions (itβs better to move them in a separate file) to make sure that they do not use the properties and methods of the ViewController instance.
In mergeImages I deleted:
let size = self.imgBackground.frame.size
and replaced size with img.size . This is the same as using self.imgBackground.image!.size , as you described in the question.
Since the source and target image sizes are the same, there is no need to adjust the aspect, and we just replace:
img.draw(in: getAspectFitFrame(sizeImgView: size, sizeImage: img.size))
with
img.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: img.size))
I also highlighted the calculation of the factor coefficient to separate the getFactor function to make the code more granular and make getAspectFitFrame return not only CGRect , but also the factor aspect (this will be useful later).
Now the utility functions look like this:
static func mergeImages(img: UIImage, sizeWaterMark: CGRect, waterMarkImage: UIImage) -> UIImage { UIGraphicsBeginImageContextWithOptions(img.size, false, UIScreen.main.scale) img.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: img.size)) let (frameAspect, _) = getAspectFitFrame(from: sizeWaterMark.size, to: waterMarkImage.size) let frameOrig = CGRect(x: sizeWaterMark.origin.x + frameAspect.origin.x, y: sizeWaterMark.origin.y + frameAspect.origin.y, width: frameAspect.size.width, height: frameAspect.size.height) waterMarkImage.draw(in: frameOrig, blendMode: .normal, alpha: 1) let result = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return result } static func getAspectFitFrame(from: CGSize, to: CGSize) -> (CGRect, CGFloat) { let (hfactor, vfactor, factor) = ViewController.getFactor(from: from, to: to)
You also need another utility function for calculating the scale and size of marked water:
static func getScaledFrame(from: CGSize, to: CGSize, target: CGRect) -> CGRect { let (aspectFitFrame, factor) = ViewController.getAspectFitFrame(from: from, to: to) return CGRect( origin: CGPoint( x: (target.origin.x - aspectFitFrame.origin.x) * factor, y: (target.origin.y - aspectFitFrame.origin.y) * factor), size: CGSize(width: target.width * factor, height: target.height * factor) ) }
You are now ready to display the merged image:
let previewImage = ViewController.mergeImages( img: imgBackground.image!, sizeWaterMark: ViewController.getScaledFrame(from: imgBackground.frame.size, to: imgBackground.image!.size, target: imgForeground.frame), waterMarkImage: imgForeground.image! )