Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active April 27, 2022 17:43
Show Gist options
  • Select an option

  • Save andresr-dev/0130e8415b84ba8af8f133bcbed60131 to your computer and use it in GitHub Desktop.

Select an option

Save andresr-dev/0130e8415b84ba8af8f133bcbed60131 to your computer and use it in GitHub Desktop.
This is an example of how you can use CoreImage Filters in your SwiftUI Apps
import SwiftUI
import CoreImage
import CoreImage.CIFilterBuiltins
struct CoreImageExample: View {
@State private var image: Image?
// We can have a filter picker in order to make this property dynamic
@State private var currentFilter: CIFilter = CIFilter.sepiaTone()
@State private var filterIntensity = 0.5
let context = CIContext()
var body: some View {
VStack {
image?
.resizable()
.scaledToFit()
HStack {
Text("Intensity")
Slider(value: $filterIntensity)
.onChange(of: filterIntensity) { _ in
applyProcessing()
}
}
.padding(.vertical)
}
.padding()
.onAppear(perform: loadImage)
}
func loadImage() {
guard let inputImage = UIImage(named: "Example") else { return }
let beginCIImage = CIImage(image: inputImage)
currentFilter.setValue(beginCIImage, forKey: kCIInputImageKey)
applyProcessing()
}
func applyProcessing() {
let currentFilterKeys = currentFilter.inputKeys
if currentFilterKeys.contains(kCIInputIntensityKey) {
currentFilter.setValue(Float(filterIntensity), forKey: kCIInputIntensityKey)
}
guard let outputCIImage = currentFilter.outputImage else { return }
if let cgImage = context.createCGImage(outputCIImage, from: outputCIImage.extent) {
let uiImage = UIImage(cgImage: cgImage)
image = Image(uiImage: uiImage)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment