ios - 合并两个 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:截图和编辑页面为横屏模式
解决方案
在 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
}
推荐阅读
- mysql - 已解决-续集-ORM-关联不起作用
- python - Tkinter Entry .get 从定义
- azure-ad-b2c - 由于缺少声明信息,向 Azure AD B2C 自定义策略注册失败
- node.js - Discord.js TypeError:无法读取未定义的属性“添加”
- postgresql - Postgres Copy To CSV Array 是双引号
- html - 如何验证带有标签的 alt 文本的正确用法
- hadoop - 如何从同一网络上的另一台机器访问 Hadoop?
- reactjs - 为什么 useEffect 挂钩不触发依赖数组中的对象?
- rsync - 是否有任何操作员使用 Airflow 通过 SFTP 在不同主机之间移动文件?
- sql - ORA-30926: 在 oracle 的合并查询中无法在源表中获得一组稳定的行