40 - Apply a Filter to an Image in SwiftUI

Sometimes, we need to apply filters to images to enhance their appearance or improve their quality. SwiftUI can use Core Image built-in filters to manipulate images with ease.

Here’s an example of applying a filter to an image in SwiftUI:

import SwiftUI
import CoreImage
import CoreImage.CIFilterBuiltins

struct ContentView: View {
  let image: Image

  init() {
    let uiImage = UIImage(named: "CoolCat") ?? UIImage()
    let filteredUIImage = ContentView.applySepiaFilter(to: uiImage)
    image = Image(uiImage: filteredUIImage)
  }

  var body: some View {
    image
      .resizable()
      .scaledToFit()
  }

  static func applySepiaFilter(to inputImage: UIImage) -> UIImage {
    guard let ciImage = CIImage(image: inputImage) else { return inputImage }

    let filter = CIFilter.sepiaTone()
    filter.inputImage = ciImage
    filter.intensity = 1.0

    // Get a CIContext
    let context = CIContext()

    // Create a CGImage from the CIImage
    guard let outputCIImage = filter.outputImage,
          let cgImage = context.createCGImage(outputCIImage, from: outputCIImage.extent) else {
      return inputImage
    }

    // Create a UIImage from the CGImage
    let outputUIImage = UIImage(cgImage: cgImage)

    return outputUIImage
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

The preview should look as follows:

You can use CoreImage filters in SwiftUI.

Here’s how this code works, beginning with the init method:

In summary, this SwiftUI view will display an image named CoolCat from the app’s resources with a sepia tone filter applied. If the image doesn’t exist or the filter can’t be applied for some reason, it will display an empty image.

Core Image Filter Choices

Here are some other Core Image filters to try:

For instance, to create a Gaussian blur filter, you would use the CIFilter.gaussianBlur() method. Similarly, for color inversion, you’d use CIFilter.colorInvert(), and so on.

You can use any of the built-in filters to manipulate the image appearance and create stunning effects. With the addition of filters, we can now enhance the visual appeal of our app’s user interface.