In my project, I want to combine two CIImages together. To do this I use "CISourceInCompositing"
if let currentFilter = CIFilter(name: "CISourceInCompositing") {
let bgImage = inputImage
var filterImage = resizeCIImage(image: filterImage, newWSize: bgImage.extent.size)
filterImage = setOpacity(image: filterImage, alpha: opacity)
currentFilter.setValue(filterImage, forKey: kCIInputImageKey)
currentFilter.setValue(bgImage, forKey: kCIInputBackgroundImageKey)
guard let outputImage = currentFilter.outputImage else {
return CIImage()
}
return outputImage
}
But I want to change the opacity of the "kCIInputImageKey" So I use this method:
func setOpacity (image : CIImage, alpha : Double) ->CIImage {
guard let overlayFilter: CIFilter = CIFilter(name: "CIColorMatrix") else { fatalError() }
let overlayRgba: [CGFloat] = [0, 0, 0, alpha]
let alphaVector: CIVector = CIVector(values: overlayRgba, count: 4)
overlayFilter.setValue(image, forKey: kCIInputImageKey)
overlayFilter.setValue(alphaVector, forKey: "inputAVector")
return overlayFilter.outputImage!
}
But the image that I obtain different than what I want:
Do you have any solution? Thanks
You should use CISourceOverCompositing
instead of CISourceInCompositing
.
Definition of CISourceInCompositing
:
Uses the background image to define what to leave in the input image, effectively cropping the input image.
Definition of CISourceOverCompositing
Places the input image over the input background image.
See information and sample outputs for other CoreImage composite operations here: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CISourceOverCompositing