简体   繁体   中英

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. 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 .

.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(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 . 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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