swift - SwiftUI - 为图像的一个边缘添加边框
问题描述
这是一个非常直接的问题 - 如何使用 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
}
}
推荐阅读
- linux - 尝试在 Suse 上运行 g_bus_own_name 时未定义的符号
- javascript - 文件上传ajax php post
- javascript - 在 Chrome 扩展程序中创建上下文菜单时出错
- google-cloud-platform - 为云 AutoML 导入谷歌云时出错
- javascript - Content Security Policy
- python - 分发关键字参数的最佳方法?
- node.js - MEAN stack app not opens from instagram profile
- amazon-web-services - s3列表对象使用sdk返回null
- asp.net-core - Using yarn to add a package removes existing modules
- ios - iPhone XR 返回正确的 nativeBounds 但设备上的屏幕尺寸错误