我想水平拼接多个图像并将其保存为一个图像。在this问题下,我发现了这个建议的解决方案:
import UIKit
import AVFoundation
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
}
但是,我不知道如何使用它。有人可以举例说明如何将它与图像数组一起使用吗?
谢谢!
答案 0 :(得分:2)
真的?
您找到的代码完全是您正在寻找的代码,但您不知道如何调用它?
如果你无法弄清楚如何调用一个函数,那么以一种有用的方式帮助你会有点困难。这里有一些通用代码可以加载一组图像并将它们拼接在一起:
//Create an array of image names
let imageNames = ["Fish", "Dog", "Eggplant", "Wombat"]
//create an array of images with those names (images must exist in app bundle)
let images = imageNames.flatMap{UIImage(named:$0)}
//Stitch the images together horizontally
let stichedImage = stitchImages(images: images, isVertical: false)
你应该停下来并对Swift做一些阅读。我建议下载Apple Swift书并阅读。它非常好,而且非常容易理解。这就是我学习语言的方式。
答案 1 :(得分:1)
有一些更新 斯威夫特4
extension Array where Element: UIImage {
func stitchImages(isVertical: Bool) -> UIImage {
let maxWidth = self.compactMap { $0.size.width }.max()
let maxHeight = self.compactMap { $0.size.height }.max()
let maxSize = CGSize(width: maxWidth ?? 0, height: maxHeight ?? 0)
let totalSize = isVertical ?
CGSize(width: maxSize.width, height: maxSize.height * (CGFloat)(self.count))
: CGSize(width: maxSize.width * (CGFloat)(self.count), height: maxSize.height)
let renderer = UIGraphicsImageRenderer(size: totalSize)
return renderer.image { (context) in
for (index, image) in self.enumerated() {
let rect = AVMakeRect(aspectRatio: image.size, insideRect: isVertical ?
CGRect(x: 0, y: maxSize.height * CGFloat(index), width: maxSize.width, height: maxSize.height) :
CGRect(x: maxSize.width * CGFloat(index), y: 0, width: maxSize.width, height: maxSize.height))
image.draw(in: rect)
}
}
}
}