Categories
Apple Swift SwiftUI

Extension for inverting the Color of your image in SwiftUI based on .dark or .light theme

I am using this little extension to invert the colors of the icons in my app. The icons are in black and white, and designed first to be used in the .light theme mode, that means they have beed design in black lines, so when the user will switch to dark, the icons should change the lines to white.

struct DetectThemeChange: ViewModifier {
    @Environment(\.colorScheme) var colorScheme

    func body(content: Content) -> some View {
        
        if(colorScheme == .dark){
            content.colorInvert()
        }else{
            content
        }
    }
}

extension View {
    func invertOnDarkTheme() -> some View {
        modifier(DetectThemeChange())
    }
}

//usage example

Image("iconName").resizable().scaledToFit().frame(height: 40).invertOnDarkTheme()

That’s it, now let’s get back to WWDC2022 which will start in a couple of hours.

By Cosmin Dolha

Cosmin Dolha, born in 1982 in Arad, Romania, is a dedicated programmer and digital artist with over 19 years of experience in the field. Married to his best friend, Cosmin is a proud father of two wonderful boys.

Throughout his career, Cosmin has designed and developed web apps, RIAS, real-time apps, and mobile applications for clients in the United States. He has also created around 25 educational games using AS3 and Haxe and has spent a year working with Unity for VR, ECS, and C# for Oculus GO.

Presently, Cosmin focuses on using Swift (Apple) to build software tools that incorporate GPT and Azure Cognitive Services. His interests extend beyond programming and include art, music, photography, 3D modeling (Zbrush, Blender), behavioral science, and neuropsychology, with a particular focus on the processing of visual information.

Cosmin is an avid podcast listener, with Lex Fridman, Andrew Huberman, and Eric Weinstein among his favorites. His reading list can be found on Goodreads, providing further insight into his interests: https://www.goodreads.com/review/list/78047933?shelf=%23ALL%23

His top 10 songs, available as a YouTube playlist, showcase his taste in music: https://www.youtube.com/playlist?list=PL5aMgX67sX9XltpvlYoih7BRAZwMrckSB

For inquiries or collaboration, Cosmin can be reached via email at contact@cosmindolha.com.