Blur in swiftUI2.0

Swift 2 introduced a new modifier for blurring views, but sometimes this blur does not look quite right. So when blurring text, use the blur modifier. When blurring a background, use a ZStack with a UIViewRepresentable and pass it a blur view.

blurred text
blurred background
import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ZStack {
            coloredView
            VisualEffectView(effect: UIBlurEffect(style: .light)).edgesIgnoringSafeArea(.all)
            Text("We can make either the text\nor the background blurry")
                .foregroundColor(Color.white)
                .font(.title2)
                .fontWeight(.bold)
        }
    }
    
    // four quadrants of color
    var coloredView: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                Rectangle()
                    .fill(Color.blue)
                Rectangle()
                    .fill(Color.green)
            }
            HStack(spacing: 0) {
                Rectangle()
                    .fill(Color.red)
                Rectangle()
                    .fill(Color.yellow)
            }
        }
        .edgesIgnoringSafeArea(.all)
    }
}

struct VisualEffectView: UIViewRepresentable {
    var effect: UIVisualEffect?
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView { UIVisualEffectView() }
    func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *