如何使用 SwiftUI 在具有透明背景的视图上裁剪阴影?
我想要实现的是有可能在 RoundedRectangle 之外裁剪阴影而不在其内部显示阴影。 (你可以看到 - “文本”有一些黑色背景,这是阴影)
我尝试实现的目标:(使用 CSS 完成此操作)- 里面的背景具有透明度
我的结果:
Text("Text")
.multilineTextAlignment(.leading)
.padding(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14))
.font(.system(size: 13, weight: .medium, design: .default))
.overlay(RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(Color.init(Color.RGBColorSpace.sRGB, white: 1, opacity: 0.2))
.shadow(color: Color.black, radius: 6, x: 0, y: 3)).padding(30)
答案 0 :(得分:2)
struct ContentView: View {
var body: some View {
ZStack {
Color.red.frame(width: 60, height: 30, alignment: .center)
.cornerRadius(10)
.shadow(color: Color.gray, radius: 1.0, x: CGFloat(4), y: CGFloat(4))
.overlay(Text("Text"))
}
}
}
结果:
欲了解更多信息,请阅读此page。
答案 1 :(得分:0)
如果也可以有一定的模糊效果,你可以使用一个显示 UIBlurEffect
作为文本背景的视图。您仍将获得透明效果,但现在具有不会弄乱阴影的不透明视图。
代码:
ZStack {
Color.blue
Text("Hello, World!")
.padding(7)
.background(BlurView(style: .systemUltraThinMaterial))
.clipShape(RoundedRectangle(cornerRadius: 10.0))
.shadow(color: Color.black.opacity(0.5), radius: 6, x: 0, y: 3)
}
结果:
而 BlurView
只是围绕 UIVisualEffectView
的 SwifUI 包装器
struct BlurView: UIViewRepresentable {
typealias UIViewType = UIVisualEffectView
let style: UIBlurEffect.Style
init(style: UIBlurEffect.Style = .systemMaterial) { self.style = style }
func makeUIView(context: Context) -> UIVisualEffectView {
return UIVisualEffectView(effect: UIBlurEffect(style: style))
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.effect = UIBlurEffect(style: style)
}
}