首页 > 解决方案 > SwiftUI - 为图像的一个边缘添加边框

问题描述

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

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

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

任何帮助表示赞赏!

标签: swiftimageuiimageswiftui

解决方案


演示

演示


执行

你可以在任何地方使用这个修饰符 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
    }
}

推荐阅读