Stitch/Composite multiple images vertically and save as one image (iOS, objective-c)

前端 未结 6 1759
一向
一向 2020-12-12 19:48

I need help writing an objective-c function that will take in an array of UIImages/PNGs, and return/save one tall image of all the images stitched together in order vertical

6条回答
  •  囚心锁ツ
    2020-12-12 20:23

    Swift 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)
                }
            }
        }
    }
    

提交回复
热议问题