Is it possible to use a views .mask(...)
modifier together with a grayscale image. I mean just like one uses a layer mask in Photoshop.
While it is not problem to use an Image
as mask view, this results in a simple rectangle mask with the size of the image. The image content is not considered for masking.
I would like use an image as mask to apply a complex opacity mask, e.g. like the cloud in
CodePudding user response:
The key here is to convert the image to use alpha depending on luminance - a perfect use for the
Code:
struct ContentView: View {
var body: some View {
Text("This is a red view with some text") // 1
.padding(50)
.background(Color.red)
.mask { // 2
Image("cloud") // 3
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 350)
.luminanceToAlpha() // 4
.fixedSize() // 5
}
}
}
How it works:
- Text is made, surrounded by padding, with a red background
- We mask the image after applying transformations
- The image is first resized to fit a 350px width
- The image is converted from grayscale to alpha
- The image is a fixed size, meaning it can't be influenced by the space given by the mask