magnuskahr

writing code

Blendmode trick: SwiftUI reverse mask

SwiftUI has the mask(alignment:_:) modifier that masks the view using the alpha channel of the given view. The reverse function is not part of SwiftUI though, but can easely be made using a blendmode trick.

See also my earlier post: Blendmode trick: SwiftUI source overlay.

The reverse mask modifier goes as following - notice the use of mask and blendmode:

extension View {
    @inlinable
    public func reverseMask<Mask: View>(alignment: Alignment = .center, @ViewBuilder _ mask: () -> Mask) -> some View {
        self.mask(
            Rectangle()
                .overlay(alignment: alignment) {
                    mask()
                        .blendMode(.destinationOut)
                }
        )
    }
}