Home > Net >  Is it possible to apply a grayscale image as view mask in SwiftUI?
Is it possible to apply a grayscale image as view mask in SwiftUI?

Time:09-10

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 enter image description here

CodePudding user response:

The key here is to convert the image to use alpha depending on luminance - a perfect use for the Text on red background masked by cloud texture

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:

  1. Text is made, surrounded by padding, with a red background
  2. We mask the image after applying transformations
  3. The image is first resized to fit a 350px width
  4. The image is converted from grayscale to alpha
  5. The image is a fixed size, meaning it can't be influenced by the space given by the mask
  • Related