SwiftUI - 将边框添加到图像的一个边缘

SwiftUI - Add Border to One Edge of an Image

这是一个非常直接的问题 - 如何使用 SwiftUI 将边框效果仅应用于图像的所需边缘?

例如,我只想在图像的顶部和底部边缘应用边框,因为图像占据了整个屏幕宽度。

Image(mission.missionImageString)
    .resizable()
    .aspectRatio(contentMode: .fit)
    .border(Color.white, width: 2) //Adds a border to all 4 edges

感谢任何帮助!

演示


实施

您可以在任何上使用这个修饰符 View:

.border(width: 5, edges: [.top, .leading], color: .yellow)

借助这个简单的扩展:

extension View {
    func border(width: CGFloat, edges: [Edge], color: Color) -> some View {
        overlay(EdgeBorder(width: width, edges: edges).foregroundColor(color))
    }
}

这是背后的神奇结构:

struct EdgeBorder: Shape {

    var width: CGFloat
    var edges: [Edge]

    func path(in rect: CGRect) -> Path {
        var path = Path()
        for edge in edges {
            var x: CGFloat {
                switch edge {
                case .top, .bottom, .leading: return rect.minX
                case .trailing: return rect.maxX - width
                }
            }

            var y: CGFloat {
                switch edge {
                case .top, .leading, .trailing: return rect.minY
                case .bottom: return rect.maxY - width
                }
            }

            var w: CGFloat {
                switch edge {
                case .top, .bottom: return rect.width
                case .leading, .trailing: return self.width
                }
            }

            var h: CGFloat {
                switch edge {
                case .top, .bottom: return self.width
                case .leading, .trailing: return rect.height
                }
            }
            path.addPath(Path(CGRect(x: x, y: y, width: w, height: h)))
        }
        return path
    }
}

如果有人只需要向视图添加一个快速的单边(或多边)边框(例如,顶部边缘,或边缘的任何随机组合),我发现这很有效并且可以调整:

顶边:

.overlay(Rectangle().frame(width: nil, height: 1, alignment: .top).foregroundColor(Color.gray), alignment: .top)

前沿:

.overlay(Rectangle().frame(width: 1, height: nil, alignment: .leading).foregroundColor(Color.gray), alignment: .leading)

等等

只需调整高度、宽度和边缘即可生成您想要的边框组合。

如果不需要控制粗细,可以这样做:

.overlay(Divider(), alignment: .top)
.overlay(Divider(), alignment: .bottom)

使用以下方法设置分隔线的颜色:

.overlay(Divider().background(.red), alignment: .left)