簡體   English   中英

SwiftUI - 如何只在頂部顯示陰影?

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

我正在嘗試為我的 VStack(僅在頂部)添加陰影,但是當我喜歡下面的陰影時,所有方面都可以看到陰影,例如按鈕、文本。 但我試圖只給容器邊界。

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

我想要如下的用戶界面在此處輸入圖像描述

謝謝你的幫助

嘗試使用mask(_:)修飾符,如本答案所示。

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

結果:

紅色陰影僅在頂部

您可以在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()...
}

結果:

頂部陰影示例

因為您只希望陰影出現在頂部,所以最好使用.shadow的偏移值。 我建議將它移動大約兩倍的半徑。

像這樣:

.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