Search code examples
iosswiftswiftuiios16

Invert image captured from ImageRenderer


I have an image (outlined in red) displaying the result of ImageRenderer called on a canvas. I want to invert the colors such that the tiny resulting image is white text on a black background. I've tried various methods from stackoverflow to invert the colors but each results in a blank result. I'm fairly new to Swift and iOS development, whats the easiest way to invert the colors of that smaller result image?

      Button(action: {
        guard let image = ImageRenderer(content: canvas).uiImage else {
          // failed to render view as image
          return
        }
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        resultImage = Image(uiImage: image)
      }){
        Text("Analyze")
      }

Image of simulator showing canvas view and smaller view of the image derived from the canvas drawing


Solution

  • enter image description here

    ColorInvert enables you to implement the features you want.

    import SwiftUI
    
    struct ContentView: View {
        
        var body: some View {
            
            VStack {
                Image("sample")
                    .colorInvert()
                    .padding()
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }