Jus*_*zer 22 image uiimage swift swiftui
这是一个非常直接的问题 - 如何使用 SwiftUI 仅将边框效果应用于图像的所需边缘?
例如,我只想在图像的顶部和底部边缘应用边框,因为图像占据了整个屏幕宽度。
Image(mission.missionImageString)
.resizable()
.aspectRatio(contentMode: .fit)
.border(Color.white, width: 2) //Adds a border to all 4 edges
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏!
Moj*_*ini 49
您可以使用此修改器上的任何 View:
.border(width: 5, edges: [.top, .leading], color: .yellow)
Run Code Online (Sandbox Code Playgroud)
在这个简单扩展的帮助下:
extension View {
func border(width: CGFloat, edges: [Edge], color: Color) -> some View {
overlay(EdgeBorder(width: width, edges: edges).foregroundColor(color))
}
}
Run Code Online (Sandbox Code Playgroud)
这是这背后的神奇结构:
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
}
}
Run Code Online (Sandbox Code Playgroud)
sma*_*kus 29
如果有人需要为视图添加一个快速的 1(或更多)边边框(例如,顶部边缘或边缘的任何随机组合),我发现这很有效并且可以调整:
顶部边缘:
.overlay(Rectangle().frame(width: nil, height: 1, alignment: .top).foregroundColor(Color.gray), alignment: .top)
Run Code Online (Sandbox Code Playgroud)
前沿:
.overlay(Rectangle().frame(width: 1, height: nil, alignment: .leading).foregroundColor(Color.gray), alignment: .leading)
Run Code Online (Sandbox Code Playgroud)
等等。
只需调整高度、宽度和边缘即可生成您想要的边框组合。
She*_*deh 11
与@smakus 类似,如果您不需要控制颜色或粗细,您可以这样做:
.overlay(Divider(), alignment: .top)
.overlay(Divider(), alignment: .bottom)
Run Code Online (Sandbox Code Playgroud)
小智 6
添加顶部边框又名分隔线:
.overlay( Divider()
.frame(maxWidth: .infinity, maxHeight:1)
.background(Color.green), alignment: .top)
Run Code Online (Sandbox Code Playgroud)
用法示例:
Image("YouImageName")
.resizable()
.scaledToFit()
.frame(height: 40)
.padding(.top, 6) // padding above you Image, before your border
.overlay( Divider()
.frame(maxWidth: .infinity, maxHeight:1)
.background(Color.green), alignment: .top) // End Overlay
.padding(.top, 0) // padding above border
Run Code Online (Sandbox Code Playgroud)
解释:
对于水平边框(又称分隔线),框架宽度是边框的长度,高度是边框的厚度。垂直边框的框架宽度是厚度,框架高度是长度。
.background 将设置边框的颜色。
将设置对齐方式,即绘制边框的位置。例如,“alignment: .bottom”会将边框放置在图像的底部,“alignment: .top”将放置在图像的顶部。
“.leading & .trailing”将相应地在图像的左侧和右侧绘制边框。
对于垂直边框:
.overlay( Divider()
.frame(maxWidth: 1, maxHeight: .infinity)
.background(Color.green), alignment: .leading )
Run Code Online (Sandbox Code Playgroud)