Skip to content

Instantly share code, notes, and snippets.

@buh
Last active February 19, 2025 11:46
Show Gist options
  • Save buh/55e684cab97ebd903b31b5d3e9dde0ba to your computer and use it in GitHub Desktop.
Save buh/55e684cab97ebd903b31b5d3e9dde0ba to your computer and use it in GitHub Desktop.
Reversed Mask for SwiftUI. Crops this view using the alpha channel of the given view.
import SwiftUI
extension View {
/// Crops this view using the alpha channel of the given view.
/// - Parameters:
/// - alignment: The alignment for mask in relation to this view.
/// - mask: The view whose alpha the rendering system applies to the specified view.
public func reversedMask<Mask: View>(
alignment: Alignment = .center,
@ViewBuilder _ mask: () -> Mask
) -> some View {
self.mask(alignment: alignment) {
ZStack {
self.saturation(0).brightness(1)
mask().saturation(0).brightness(-1)
}
.compositingGroup()
.luminanceToAlpha()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment