Last active
October 30, 2021 09:11
-
-
Save A-Zak/3c38d3f83f911a25790f to your computer and use it in GitHub Desktop.
UIImage extension to combine two images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIImage { | |
class func imageByCombiningImage(firstImage: UIImage, withImage secondImage: UIImage) -> UIImage { | |
let newImageWidth = max(firstImage.size.width, secondImage.size.width ) | |
let newImageHeight = max(firstImage.size.height, secondImage.size.height) | |
let newImageSize = CGSize(width : newImageWidth, height: newImageHeight) | |
UIGraphicsBeginImageContextWithOptions(newImageSize, false, UIScreen.mainScreen().scale) | |
let firstImageDrawX = round((newImageSize.width - firstImage.size.width ) / 2) | |
let firstImageDrawY = round((newImageSize.height - firstImage.size.height ) / 2) | |
let secondImageDrawX = round((newImageSize.width - secondImage.size.width ) / 2) | |
let secondImageDrawY = round((newImageSize.height - secondImage.size.height) / 2) | |
firstImage .drawAtPoint(CGPoint(x: firstImageDrawX, y: firstImageDrawY)) | |
secondImage.drawAtPoint(CGPoint(x: secondImageDrawX, y: secondImageDrawY)) | |
let image = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return image | |
} | |
} |
not very smart. You're calling this already on an image instance, why passing both images as parameters?
We don't need to write first image. Let's look with point parameter:
Swift 5.x
// MARK: Merge Image
extension UIImage {
func mergeImage(with secondImage: UIImage, point: CGPoint? = nil) -> UIImage {
let firstImage = self
let newImageWidth = max(firstImage.size.width, secondImage.size.width)
let newImageHeight = max(firstImage.size.height, secondImage.size.height)
let newImageSize = CGSize(width: newImageWidth, height: newImageHeight)
UIGraphicsBeginImageContextWithOptions(newImageSize, false, deviceScale)
let firstImagePoint = CGPoint(x: round((newImageSize.width - firstImage.size.width) / 2),
y: round((newImageSize.height - firstImage.size.height) / 2))
let secondImagePoint = point ?? CGPoint(x: round((newImageSize.width - secondImage.size.width) / 2),
y: round((newImageSize.height - secondImage.size.height) / 2))
firstImage.draw(at: firstImagePoint)
secondImage.draw(at: secondImagePoint)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? self
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 3.x