【问题标题】:SwiftUI - Add Border to One Edge of an ImageSwiftUI - 为图像的一个边缘添加边框
【发布时间】:2020-02-26 03:42:47
【问题描述】:

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

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

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

感谢您的帮助!

【问题讨论】:

    标签: swift image uiimage swiftui


    【解决方案1】:

    类似于@smakus,如果你不需要控制颜色或厚度,你可以这样做:

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

    【讨论】:

    • 您可以使用 Divider().background(Color.red) 更改 Divider 颜色
    【解决方案2】:

    演示


    实施

    您可以在 any 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
        }
    }
    

    【讨论】:

    • 代码增加了一些间距,占据了整个空间。
    • 将“魔术”代码(body 中的块)放在我的形状的 .overlay 内效果很好。感谢您提供此代码!
    【解决方案3】:

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

    顶边:

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

    等等

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 2021-07-13
      • 2023-02-06
      • 2015-10-06
      • 1970-01-01
      • 2014-04-11
      • 2023-04-02
      相关资源
      最近更新 更多