如何在保持宽高比和尺寸的同时合并两个UIImage? [英] How to merge two UIImages while keeping the aspect ratio and size?
本文介绍了如何在保持宽高比和尺寸的同时合并两个UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码已添加到 Github 中,以使您了解真正的问题.
The code is added to Github to let you understand the real problem.
这是层次结构:
-- 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)]
我正在尝试将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
}
注意:
- .contentMode = .scaleAspectFit
- 代码有效,但结果得到了扩展.
- 请参见代码
let size = self.imgBackground.frame.size
中的此行–我需要更改此行以解决问题. 找到关于UIImage大小的子视图的来源
- .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?
推荐答案
您的代码中有两个错误:
You have two bugs in your code:
-
您还应该计算文档图像的长宽比以适合
UIImageView
.在mergeImages()
中替换:
img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
具有:
img.draw(in: getAspectFitFrame(sizeImgView: size, sizeImage: img.size))
在计算宽高比时,如果宽度/高度小于UIImageView
宽度/高度,则可以水平/垂直居中放置图像.但是,除了比较newWidth
和newHeight
之外,您还应该比较因素:
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
}
这篇关于如何在保持宽高比和尺寸的同时合并两个UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文