【问题标题】:Align masked Rectangle in a ZStack while also changing masked area [SwiftUI]在 ZStack 中对齐蒙版矩形,同时更改蒙版区域 [SwiftUI]
【发布时间】:2020-12-13 21:33:24
【问题描述】:

对于评级显示,我试图将图像分成两部分,黑色和红色部分,我希望红色部分占据整个图像的特定百分比。我遇到的问题是矩形与另一个图像的中心对齐,当将 ZStack 的对齐更改为.leading 时,矩形确实移动了,但不幸的是图像的蒙版区域没有改变。

ZStack {
    Image("Car")
            
    Rectangle()
        .foregroundColor(ColorManager.brand)
        .frame(width: 20.0, height: 20.0)
        .mask(Image("Car"))
}

Without alignment

ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
    Image("Car")
            
    Rectangle()
        .foregroundColor(ColorManager.brand)
        .frame(width: 20.0, height: 20.0)
        .mask(Image("Car"))
}

With alignment

如何将 Rectangle 的对齐方式更改为 .leading,同时屏蔽图像的前导部分?

编辑:Desired effect

【问题讨论】:

  • 我无法理解你到底想达到什么目的?
  • 我添加了另一张图片以显示所需的效果。

标签: swiftui


【解决方案1】:

您只需在需要的位置进行剪辑。这是可能方法的完整演示(在自定义 CarView 上,因为我没有像您这样的汽车图像)。

使用 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))
    )

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多