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

前端 未结 6 1898
一向
一向 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:39

    The solutions above were helpful but had a serious flaw for me. The problem is that if the images are of different sizes, the resulting stitched image would have potentially large spaces between the parts. The solution I came up with combines all images right below each other so that it looks like more like a single image no matter the individual image sizes.

    For Swift 3.x

    static func combineImages(images:[UIImage]) -> UIImage
    {
        var maxHeight:CGFloat = 0.0
        var maxWidth:CGFloat = 0.0
    
        for image in images
        {
            maxHeight += image.size.height
            if image.size.width > maxWidth
            {
                maxWidth = image.size.width
            }
        }
    
        let finalSize = CGSize(width: maxWidth, height: maxHeight)
    
        UIGraphicsBeginImageContext(finalSize)
    
        var runningHeight: CGFloat = 0.0
    
        for image in images
        {
            image.draw(in: CGRect(x: 0.0, y: runningHeight, width: image.size.width, height: image.size.height))
            runningHeight += image.size.height
        }
    
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return finalImage!
    }
    

提交回复
热议问题