Swiftui - 添加模糊线性渐变

The*_*der 4 swiftui

我想在图像顶部添加白色文本。我的策略是添加一个在文本区域模糊的渐变(请检查附图)

有人知道如何做到这一点吗?

检查图像

ahe*_*eze 14

这个怎么样?

结果图像

对于模糊效果,只需使用.blur()修改器 - 不需要单独的模糊图像。

struct ContentView: View {
    
    let gradient = LinearGradient(
        gradient: Gradient(stops: [
            .init(color: .purple, location: 0),
            .init(color: .clear, location: 0.4)
        ]),
        startPoint: .bottom,
        endPoint: .top
    )
    
    var body: some View {
        Image("Background")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .overlay(
                ZStack(alignment: .bottom) {
                    Image("Background")
                        .resizable()
                        .blur(radius: 20) /// blur the image
                        .padding(-20) /// expand the blur a bit to cover the edges
                        .clipped() /// prevent blur overflow
                        .mask(gradient) /// mask the blurred image using the gradient's alpha values
                    
                    gradient /// also add the gradient as an overlay (this time, the purple will show up)
                    
                    HStack {
                        Image("Icon") /// app icon
                            .resizable()
                            .frame(width: 64, height: 64)
                        
                        VStack(alignment: .leading) {
                            Text("Classroom of the Elite")
                                .bold()
                            Text("Horikita best girl")
                                .opacity(0.75)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading) /// allow text to expand horizontally
                        
                        Button { } label: {
                            Text("GET")
                                .bold()
                                .padding(8)
                                .background(Color.gray)
                                .cornerRadius(16)
                        }
                    }
                    .foregroundColor(.white)
                    .padding(20)
                }
            )
    }
}
Run Code Online (Sandbox Code Playgroud)