文本不透明度渐变

Geo*_*e_E 3 blending swift swiftui

我希望使文本看起来在边缘淡出。这是我到目前为止所拥有的:

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red

            Text("Hello world!")
//                .blendMode(.luminosity) // <- Here?
                .overlay(
                    LinearGradient(colors: [.white.opacity(0), .white], startPoint: .leading, endPoint: .trailing)
                        .frame(width: 50)
//                        .blendMode(.exclusion) // <- Here?
                        .frame(maxWidth: .infinity, alignment: .trailing)
                )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生产:

产生的结果

您可以在文本右侧看到白色渐变。这应该像一个不透明过滤器一样。在白色尚未结束的地方,文字完全可见。白色下方的文字应该是完全透明的。应该是使用渐变来逐渐过渡。

我认为可以使用 来解决这个问题blendMode(_:),但我不太确定。我不知道该使用哪种模式,也不知道在哪里应用它。

解决方案应该在明暗模式下工作(即文本可以是黑色白色)。后面的实际背景不是恒定的颜色(例如红色),因此使用红色渐变叠加不是我想要的。

ahe*_*eze 9

就用.mask代替吧。

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red
            
            Text("Hello world!")
            
            /// for iOS 14 and below, replace { } with ( )
            .mask {
                ///                             no need for .opacity, just use .clear
                LinearGradient(colors: [.white, .clear], startPoint: .leading, endPoint: .trailing)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

右侧文字淡出