如何在 SwiftUI 中复制此阴影 + 偏移

Posted

技术标签:

【中文标题】如何在 SwiftUI 中复制此阴影 + 偏移【英文标题】:How can I replicate this shadow + offset in SwiftUI 【发布时间】:2021-03-25 06:26:52 【问题描述】:

我正在尝试使用 SwiftUI 复制用 UIKit 编写的组件

这是一个看起来像这样的“阴影卡片容器”-

你看到阴影效果有一个偏移量和高度值

尝试在 SwiftUI 中创建它我无法完全正确 -

UIKit 视图是通过扩展处理的 -

public extension UIView 
    func addShadow(offset: CGSize = .init(width: 0, height: 3), color: UIColor = .init(red: 0, green: 0, blue: 0, alpha: 0.16), radius: CGFloat = 2, opacity: Float = 1) 
        layer.masksToBounds = false
        layer.shadowOffset = offset
        layer.shadowColor = color.cgColor
        layer.shadowRadius = radius
        layer.shadowOpacity = opacity
        
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
    


在视图上-


public class CardContainerView: UIView 
    
    private var didlLayoutSubviews = false
    
    public override init(frame: CGRect) 
        super.init(frame: frame)
        configureUI()
    
    
    required init?(coder: NSCoder) 
        return nil
    
    
    public override func layoutSubviews() 
        super.layoutSubviews()
        guard !didlLayoutSubviews else  return 
        didlLayoutSubviews = true
        addShadow(
            offset: .init(width: 0, height: 3),
            color: .init(red: 0, green: 0, blue: 0, alpha: 0.16),
            radius: 2
        )
    


private extension CardContainerView 
    func configureUI() 
        layer.cornerRadius = 12
        clipsToBounds = true
    


我已经在 SwiftUI 中尝试过这个并想出了 -

public struct CardView<Content>: View where Content: View 
    
    private var content: () -> Content
    
    public init(@ViewBuilder _ content: @escaping () -> Content) 
        self.content = content
    
    
    public var body: some View 
        VStack(content: content)
            .padding()
            .frame(maxWidth: .infinity, minHeight: 100, alignment: .top)
            .background(Color(.tertiarySystemBackground))
            .cornerRadius(12)
            .shadow(
                color: Color(.init(red: 0, green: 0, blue: 0, alpha: 0.16)),
                radius: 2
            )
    

我不明白如何在 SwiftUI 中将高度和偏移值应用于阴影

【问题讨论】:

.shadow(color: Color(.init(red: 0, green: 0, blue: 0, alpha: 0.16)), radius: 2, x: 0, y: 3) ? 【参考方案1】:

您可以将偏移值应用于阴影的xy 值。

VStack(content: content)
    .padding()
    .frame(maxWidth: .infinity, minHeight: 100, alignment: .top)
    .background(Color(.tertiarySystemBackground))
    .cornerRadius(12)
    .shadow(
        color: Color(.init(red: 0, green: 0, blue: 0, alpha: 0.16)),
        radius: 2,
        y: 3 // This should give you the same effect
    )

【讨论】:

以上是关于如何在 SwiftUI 中复制此阴影 + 偏移的主要内容,如果未能解决你的问题,请参考以下文章

html5如何让边框发光

删除阴影 SwiftUI 旁边的空格

SwiftUI4.0在iOS 16中新添加的inner和drop阴影效果

SwiftUI4.0在iOS 16中新添加的inner和drop阴影效果

说说在 Canvas 中如何添加阴影

SwiftUI: ScrollView offset