Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
CIFilter opacity
Change the opacity of a CIFilter.
func changeOpacity(to opacity: CGFloat, on filter: CIFilter, original image: UIImage) -> CIImage? {
guard let backgroundImage: CIImage = CIImage(image: image) else { fatalError() }
// The CIColorMatrix filter, will contain the requested filter and control its opacity
guard let overlayFilter: CIFilter = CIFilter(name: "CIColorMatrix") else { fatalError() }
let overlayRgba: [CGFloat] = [0, 0, 0, opacity]
let alphaVector: CIVector = CIVector(values: overlayRgba, count: 4)
overlayFilter.setValue(filter.outputImage!, forKey: kCIInputImageKey)
overlayFilter.setValue(alphaVector, forKey: "inputAVector")
// Compose the background and the overlay filter
guard let compositeFitler: CIFilter = CIFilter(name: "CISourceOVerCompositing") else { fatalError() }
compositeFilter.setValue(backgroundImage, forKey: kCIInputBackgroundImageKey)
compositeFilter.setValue(opacityFilter.outputImage!, forKey: kCIInputImageKey)
return compositeFilter.outputImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.