本文介绍了SwiftUI-将边框添加到图像的一个边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个非常简单的问题-使用SwiftUI如何仅对图像的所需边缘应用边框效果?
It's a pretty straight-forward question - how does one apply a border effect to only the wanted edges of an Image with SwiftUI?
例如,我只想在图像的顶部和底部边缘应用边框,因为图像占据了屏幕的整个宽度.
For example, I only want to apply a border to the top and bottom edges of an image because the image is taking up the entire width of the screen.
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
}
}
这篇关于SwiftUI-将边框添加到图像的一个边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!