简体   繁体   中英

SwiftUI: How to add Blur view with app logo when app in background?

I am new to SwiftUI. I am trying to add blur view with the app logo when the app enters into the background for hiding secure information. I tried the below code. It's showing blur as expected. But I want to display the view+app logo.

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    @State var blurRadius : CGFloat = 0
    
    var body: some View {
        VStack{
            MainView()
        }.blur(radius: blurRadius)
            .onChange(of: scenePhase, perform: { value in
                switch value {
                case .active : withAnimation { blurRadius = 0 }
                case .inactive: withAnimation { blurRadius = 15 }
                case .background:
                    blurRadius = 20
                @unknown default: print("Unknown")
                }
            })
    }
}

Result:

在此处输入图片说明

Someone please suggests how to achieve that?

You could use a ZStack and place your logo image on top whenever there's a blur in place:

struct ContentView: View {
    
    @Environment(\.scenePhase) var scenePhase
    @State var blurRadius : CGFloat = 0
    
    var body: some View {
        ZStack {
            VStack{
                MainView()
            }
            .blur(radius: blurRadius)
            .onChange(of: scenePhase, perform: { value in
                switch value {
                case .active : withAnimation { blurRadius = 0 }
                case .inactive: withAnimation { blurRadius = 15 }
                case .background:
                    blurRadius = 20
                @unknown default: print("Unknown")
                }
            })
            if blurRadius != 0 {
                Image("logo")
            }
        }
    }
}

This is assuming your app logo is added to the project's assets as "logo". Obviously, you may want to do some modifications like .resizable or .frame on the Image

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