Hi guys,
I want to apply a CIFilter on just a selected part of an image. When working with CIFilter, you get an output image. This output image
is edited but is still only a part of the origin image. I want to merge it with the original image again.
At the moment, I have following code:
let colorCube = CIFilter(name: "CIColorCube")!
colorCube.setValue(size, forKey: "inputCubeDimension")
colorCube.setValue(data, forKey: "inputCubeData")
// overlay is the selected the area, which should be edited
let partOfImage = self.imageView.image?.crop(size: overlay.frame.size, offset: overlay.frame.origin)
colorCube.setValue(partOfImage, forKey: kCIInputImageKey)
if let outImage = colorCube.outputImage {
let context = CIContext(options: nil)
// when applying CIFilter, we get an output image
let outputImageRef = context.createCGImage(outImage, from: outImage.extent)
let editedImagePart = UIImage(cgImage: outputImageRef!)
// attempt to merge output image with the original image (imageView.image)
imageView.image?.drawImageInRect(inputImage: editedImagePart, inRect: overlay.frame)
}
}
...
extension UIImage {
// attempt to merge images
func drawImageInRect(inputImage: UIImage, inRect imageRect: CGRect) -> UIImage {
UIGraphicsBeginImageContext(self.size)
self.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
inputImage.draw(in: imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
// function to crop part of the original image
func crop(size: CGSize, offset: CGPoint, scale: CGFloat = 1.0) -> UIImage? {
let rect = CGRect(x: offset.x * scale, y: offset.y * scale, width: size.width * scale, height: size.height * scale)
if let cropped = self.cgImage?.cropping(to: rect) {
return UIImage(cgImage: cropped)
}
return nil
}
}
Does anyone have an idea, how I can do that?