在ZStack中对齐遮罩矩形,同时更改遮罩区域[SwiftUI]
对于分级显示,我尝试将图像分为两部分,黑色和红色,我希望红色部分占整个图像的特定百分比。我遇到的问题是,矩形与另一幅图像的中心对齐,当ZStack的对齐方式更改为在ZStack中对齐遮罩矩形,同时更改遮罩区域[SwiftUI],swiftui,Swiftui,对于分级显示,我尝试将图像分为两部分,黑色和红色,我希望红色部分占整个图像的特定百分比。我遇到的问题是,矩形与另一幅图像的中心对齐,当ZStack的对齐方式更改为。leading时,矩形确实会移动,但不幸的是,图像的遮罩区域没有改变 ZStack{ 图像(“汽车”) 矩形() .foregroundColor(ColorManager.brand) .框架(宽度:20.0,高度:20.0) .面罩(图像(“汽车”)) } ZStack(对齐:对齐(水平:前导,垂直:中心)){ 图像(“汽车”
。leading
时,矩形确实会移动,但不幸的是,图像的遮罩区域没有改变
ZStack{
图像(“汽车”)
矩形()
.foregroundColor(ColorManager.brand)
.框架(宽度:20.0,高度:20.0)
.面罩(图像(“汽车”))
}
ZStack(对齐:对齐(水平:前导,垂直:中心)){
图像(“汽车”)
矩形()
.foregroundColor(ColorManager.brand)
.框架(宽度:20.0,高度:20.0)
.面罩(图像(“汽车”))
}
如何将矩形的对齐方式更改为.leading
,同时遮罩图像的前导部分
编辑:您只需在所需位置进行剪裁。这里是一个完整的演示可能的做法(在自定义车视图,因为我没有像你的汽车图像) 使用Xcode 12.1/iOS 14.1编写 因此,您的代码可能看起来像(当然,您可以根据需要调整掩码的大小)
您只需在需要的位置进行剪裁。这里是一个完整的演示可能的做法(在自定义车视图,因为我没有像你的汽车图像) 使用Xcode 12.1/iOS 14.1编写 因此,您的代码可能看起来像(当然,您可以根据需要调整掩码的大小)
我无法理解你到底想达到什么?我添加了另一个图像以显示所需效果。我无法理解你到底想达到什么?我添加了另一个图像以显示所需效果。
struct CarView: View {
var body: some View {
Image(systemName: "car").resizable()
.frame(width: 200, height: 80)
}
}
struct MaskShape: Shape {
var alignment: HorizontalAlignment = .center
func path(in rect: CGRect) -> Path {
switch alignment {
case .leading:
return Rectangle().path(in: rect.divided(atDistance: rect.width / 3, from: .minXEdge).slice)
case .center:
return Rectangle().path(in: rect.insetBy(dx: rect.width / 3, dy: 0))
case .trailing:
return Rectangle().path(in: rect.divided(atDistance: rect.width / 3, from: .maxXEdge).slice)
default:
return Rectangle().path(in: rect)
}
}
}
struct TestCarMaskView: View {
var body: some View {
VStack {
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape())
)
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape(alignment: .leading))
)
CarView()
.overlay(
Rectangle()
.foregroundColor(.red)
.mask(CarView())
.clipShape(MaskShape(alignment: .trailing))
)
}
}
}
Image("Car")
.overlay(
Rectangle()
.foregroundColor(ColorManager.brand)
.mask(Image("Car"))
.clipShape(MaskShape(alignment: .leading))
)