我有一个从设备相机捕获的图像,我想在其上添加一个 UITextView
,然后将其保存到图库中。我使用以下代码从 TextView 获取图像
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))
看下面的截图,可以看到大小发生了变化,位置似乎是随机选择的。知道为什么以及如何解决这个问题吗?
编辑期间:
保存后:
P.S:拍摄的图像和编辑页面为横向模式
最佳答案
在 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
}
关于ios - 合并两个 UIImages swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57064620/