Masking views using Mask Modifier in SwiftUI

DevTechie Inc
Jul 16, 2023

Masking views using Mask Modifier in SwiftUI

SwiftUI’s mask modifier is used for masking one view with another view. We use mask modifier when we want to apply the alpha (opacity) value of another view to the current view.

DevTechie
SwiftUI, iOS Development, iOS, Swift, DevTechie, Image View, SF Symbols, ios 15. iOS 16, iPadOS, watchOS, swiftui listwww.devtechie.com

Application of mask modifier is simple, let’s set Text view’s foreground color in gradient style with the help of mask modifier.

struct MaskModifierExample: View {
    var body: some View {
        LinearGradient(colors: [.pink, .blue], startPoint: .leading, endPoint: .trailing)
            .mask {
                Text("DevTechie.com")
                    .font(.system(size: 48))
            }
    }
}

We can use mask modifier to combine two images and create a new image.

struct MaskModifierExample: View {
    var body: some View {
        Image(systemName: "envelope.badge.fill")
            .font(.system(size: 128, weight: .regular))
            .mask {
                Image(systemName: "person.fill")
                    .font(.system(size: 64))
            }
            .overlay {
                Circle()
                    .stroke(lineWidth: 4)
                
            }
            .foregroundColor(Color.blue)
    }
}

We can use mask modifier to add dim effect on images.

struct MaskModifierExample: View {
    @State private var applyDim = false
    var body: some View {
        Image(systemName: "person.fill")
            .font(.system(size: 128, weight: .regular))
            .foregroundColor(.blue)
            .mask({
                Rectangle().foregroundColor(.orange.opacity(applyDim ? 0.2 : 0.8))
            })
            .onTapGesture {
                applyDim.toggle()
            }
    }
}

Mask modifier can be used to color SF symbol based images as well.

struct MaskModifierExample: View {
    @State private var gradientEndPoint: UnitPoint = .trailing
    let unitPoints: [UnitPoint] = [UnitPoint.leading, .trailing, .bottom, .bottomLeading, .bottomTrailing, .center, .top, .topLeading, .topTrailing]
    var body: some View {
        LinearGradient(colors: [.red, .blue], startPoint: .leading, endPoint: gradientEndPoint)
            .frame(width: 128, height: 128)
            .mask {
                Image(systemName: "flag.checkered")
                    .font(.system(size: 128))
            }
            .onTapGesture {
                withAnimation {
                    gradientEndPoint = unitPoints.randomElement() ?? .topTrailing
                }
            }
    }
}