简体   繁体   中英

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

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, eg like the cloud in this image

在此处输入图像描述

The key here is to convert the image to use alpha depending on luminance - a perfect use for the luminanceToAlpha() modifier.

Result:

云纹理掩盖的红色背景上的文本

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM