如何使用RoundedRectangle()实现iOS风格模糊背景效果?
问题分析
现有代码使用半透明白色作为圆角矩形背景,仅能实现纯色半透明叠加效果,无法对下层内容做模糊采样,和iOS原生毛玻璃视觉效果存在本质差异。
错误点说明
- 代码中
RoundedRectangle(cornerRadius: 20).background(Color.white.opacity(0.5))的实现逻辑,是在圆角矩形层级后方叠放一层50%透明度的白色,不会对下层的粉色背景做高斯模糊处理,自然出不来原生毛玻璃的通透模糊质感。 - iOS原生模糊效果的核心是对模糊层下方的所有内容做实时采样模糊,需要调用系统提供的模糊材质接口实现,不能用半透明纯色模拟。
正确实现(iOS 15+ 推荐,零冗余代码)
直接使用SwiftUI内置的Material材质作为填充即可,和系统原生控件的模糊效果完全一致:
import SwiftUI struct MyBackGround: View { var body: some View { ZStack { Color.pink.ignoresSafeArea() RoundedRectangle(cornerRadius: 20) // 填充系统模糊材质,可根据需要选择不同厚度 .fill(.ultraThinMaterial) // 如需微调亮感可叠加低透明度白色,不需要可删除 .overlay(Color.white.opacity(0.15)) .frame(width: 220, height: 100) } } }
可选择的材质模糊强度从弱到强(透明度从高到低)依次为:
.ultraThinMaterial:最轻薄,模糊程度最低,通透感最强.thinMaterial:轻薄材质.regularMaterial:常规厚度,系统默认弹窗、卡片常用.thickMaterial:厚重材质.ultraThickMaterial:最厚重,模糊程度最高,透明度最低
低版本兼容方案(支持iOS 13+)
如果需要兼容iOS 15以下的系统版本,可以通过UIViewRepresentable桥接UIKit的UIVisualEffectView实现:
import SwiftUI struct SystemBlurView: UIViewRepresentable { let blurStyle: UIBlurEffect.Style func makeUIView(context: Context) -> UIVisualEffectView { UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) } func updateUIView(_ uiView: UIVisualEffectView, context: Context) { uiView.effect = UIBlurEffect(style: blurStyle) } } // 使用示例 struct MyBackGround: View { var body: some View { ZStack { Color.pink.ignoresSafeArea() RoundedRectangle(cornerRadius: 20) .frame(width: 220, height: 100) .overlay { SystemBlurView(blurStyle: .systemUltraThinMaterial) .overlay(Color.white.opacity(0.15)) .clipShape(RoundedRectangle(cornerRadius: 20)) } } } }
注意:不要给承载模糊效果的形状设置纯色填充,否则纯色会完全挡住下层内容,导致模糊效果失效。
内容的提问来源于stack exchange,提问作者Steven-Carrot
相关产品推荐
相关产品推荐

