简体   繁体   English

SwiftUI - 如何只在顶部显示阴影?

[英]SwiftUI - How to show shadow only on top side?

I am trying to give shadow to my VStack (only at top) but when I do like below shadow is visible to all sides like button, Text.我正在尝试为我的 VStack(仅在顶部)添加阴影,但是当我喜欢下面的阴影时,所有方面都可以看到阴影,例如按钮、文本。 But I am trying to give border to only container.但我试图只给容器边界。

.background(Color.white // any non-transparent background
               .shadow(color: Color.red, radius: 10, x: 0, y: 0)
             )

I want UI like below我想要如下的用户界面在此处输入图像描述

Thank you for help谢谢你的帮助

Try using themask(_:) modifier, as shown in this answer .尝试使用mask(_:)修饰符,如本答案所示。

.background(
    Color.white // any non-transparent background
        .shadow(color: Color.red, radius: 10, x: 0, y: 0)
        .mask(Rectangle().padding(.top, -20)) /// here!
)

Result:结果:

红色阴影仅在顶部

You could put a LinearGradient at the top of the VStack to achieve the "top shadow" effect.您可以在VStack的顶部放置一个LinearGradient以实现“顶部阴影”效果。

VStack(spacing: 0) {
   LinearGradient(colors: [.white, Color(.sRGB, white: 0.85, opacity: 1)], startPoint: .top, endPoint: .bottom)
       .frame(height: 6)
       .opacity(0.8)

    // Button()...
}

Result:结果:

顶部阴影示例

As you only want the shadow to come on the top it would be better to use the offset values of the .shadow .因为您只希望阴影出现在顶部,所以最好使用.shadow的偏移值。 I would suggest moving it roughly double the radius.我建议将它移动大约两倍的半径。

like this:像这样:

.shadow(color: Color.red, 
        radius: 10, 
        x: -20, // Horizontal offset
        y: 0) // Vertical offset
.shadow(color: Color.black, 
        radius: 5, 
        x: 5, // (left shadow "-X" & right shadow "+X")
        y: -5) // (top shadow "-Y" & bottom shadow "+Y")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM