I have merge two images into one. I already implemented it with some help from the internet but it takes around 2,5s. I'm testing on the simulator so let's take it as a reference.
I currently use UIGraphicsBeingImageContext
. Is there any faster way to achieve it?
extension UIImage {
func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat, topImageSize: CGSize,
combinedImage: @escaping (UIImage) -> Void) {
DispatchQueue.global(qos: .userInteractive).async {
let newWidth = self.size.width < posX + image.size.width ? posX + image.size.width : self.size.width
let newHeight = self.size.height < posY + image.size.height ? posY + image.size.height : self.size.height
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(origin: CGPoint.zero, size: self.size))
image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: topImageSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
DispatchQueue.main.async {
combinedImage(newImage)
}
}
}
}
1 Answer 1
On a simulator with the original code, it takes about 1.52s
on my machine.
Since the base image won't get resized (self.size
is passed in self.draw(in:)
), and its alpha channel is always 1
, I could gain at least 200ms
by using the following :
self.draw(at: CGPoint.zero, blendMode: .copy, alpha: 1)
-
\$\begingroup\$ thanks, cool trick. I managed to drop from
1.13
s to1.07
s or even0.98
on the simulator. Not a major improvement but a welcome one. \$\endgroup\$mikro098– mikro0982018年12月25日 21:49:28 +00:00Commented Dec 25, 2018 at 21:49
topImageSize
has the same with/height ratio as the size ofimage
. Needed clarification: Could these images have some transparency, could the alpha channel be different from 1.0? \$\endgroup\$