SwiftUI MAC app 如何设置透明磨砂背景效果?

19 min read

要在SwiftUI MAC应用程序中设置透明磨砂背景,您可以使用ZStack和Blur结构体。以下是一个示例代码片段:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ZStack {
            Image("background")
                .resizable()
                .scaledToFill()
            
            Blur(effect: .regular)
            
            VStack {
                Text("Hello, World!")
                    .font(.largeTitle)
                    .bold()
                    .foregroundColor(.white)
            }
        }
        .frame(minWidth: 400, minHeight: 300)
    }
}

struct Blur: NSViewRepresentable {
    var effect: NSVisualEffectView.Material
    
    func makeNSView(context: Context) -> NSVisualEffectView {
        let view = NSVisualEffectView()
        view.blendingMode = .behindWindow
        view.material = effect
        view.state = .active
        return view
    }
    
    func updateNSView(_ nsView: NSVisualEffectView, context: Context) {
        nsView.material = effect
    }
}

在此示例中,我们使用ZStack将图像和磨砂背景堆叠在一起。我们还使用了自定义Blur结构体作为NSViewRepresentable,以便我们可以在SwiftUI中使用NSVisualEffectView。最后,我们将整个内容框架调整为具有最小宽度和高度,以适应任何屏幕大小。