Hue Rotation in SwiftUI

DevTechie Inc
Jun 24, 2022


Photo by Vackground on Unsplash

Hue, in graphics refers to the attribute of a visible light due to which it is differentiated from or similar to the primary colors which are red, green and blue. The term is also used to refer to colors that have no added tint or shade.

SwiftUI provides a hueRotation modifier which takes angle as a parameter.

If you look at the color wheel above, pick any color, apply angle to hue rotation, we get a new color. For example, if we use orange color and apply 180° rotation, we will get blue color.

Here is how that will look in SwiftUI code:

struct HueRotationExample: View {
    var body: some View {
        ZStack {
            Text("DevTechie")
                .font(.largeTitle)
                .bold()
                .foregroundColor(.white)
        }
        .frame(width: 200, height: 200)
        .background(
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(.orange)
                .hueRotation(.degrees(180))
        )
    }
}
At this point color changes without any visual transition for colors, so it would be cool if we could see this color change over time. The great thing about SwiftUI is that most of the things honor animation, so we will animate this change as well.

We will create a state property called animate to apply hue rotation and depending upon the animate to be true or false, we will adjust the angle for hue rotation. We will also toggle the animate property by adding the tapGesture modifier to ZStack.

struct HueRotationExample: View {
    @State private var animate = false
    var body: some View {
        ZStack {
            Text("DevTechie")
                .font(.largeTitle)
                .bold()
        }
        .frame(width: 200, height: 200)
        .background(
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(.orange)
                .hueRotation(.degrees(animate ? 180 : 0))
        )
        .animation(.easeInOut.speed(0.1), value: animate)
        .onTapGesture {
            animate.toggle()
        }
    }
}
With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com