swiftui

Swiftui - Add blur linear gradient


I would like to add a white text on the top of an image. My strategy will be to add a gradient that will be blurred at the text zone (please check the attached picture)

Anyone got an idea how to do this?

Check image


Solution

  • How's this?

    Image of result

    For the blur effect, just use the .blur() modifier - no need for a separate image that's blurred.

    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)
                    }
                )
        }
    }