🌅BlurView
可以讓在它下面的 view 變模糊。
Last updated
可以讓在它下面的 view 變模糊。
Last updated
import SwiftUI
// 🌅 BlurView
public struct BlurView: UIViewRepresentable {
public typealias UIViewType = UIView
let style: UIBlurEffect.Style
public init(_ style: UIBlurEffect.Style = .systemMaterial) {
self.style = style
}
public func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView {
// view (parent view)
let view = UIView(frame: CGRect.zero)
view.backgroundColor = .clear
// ⭐️ blur effect
let blurEffect = UIBlurEffect(style: style)
// ⭐️ blur view (subview)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.translatesAutoresizingMaskIntoConstraints = false // auto layout
view.insertSubview(blurView, at: 0)
// ⭐️ blurView.size == view.size
NSLayoutConstraint.activate([
blurView.widthAnchor.constraint(equalTo: view.widthAnchor),
blurView.heightAnchor.constraint(equalTo: view.heightAnchor),
])
return view
}
public func updateUIView(
_ uiView: UIView,
context : UIViewRepresentableContext<BlurView>
) { }
}
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
ZStack {
// contents below BlurView
RoundedRectangle(cornerRadius: 10)
.fill(Color.white)
.frame(width: 200, height: 150)
.overlay(Circle().fill(Color.pink).padding(30))
// contents on top of BlurView
VStack {
Capsule().fill(Color.gray.opacity(0.4))
.frame(width: 60, height: 4)
.padding(.top, 10)
.padding(.bottom, 20)
Text("Blur View")
Text("style: .systemUltraThinMaterial")
.font(.caption)
.foregroundColor(.secondary)
Spacer()
}//
.frame(maxWidth: .infinity)
// ⭐️ BlurView
.background(BlurView(.systemUltraThinMaterial))
.cornerRadius(20).offset(y: 134)
}// container (ZStack)
.padding()
.shadow(radius: 8)
.background(Color.gray)
.cornerRadius(10)
.frame(width: 400, height: 300)
}
}
PlaygroundPage.current.setLiveView(ContentView())