如何在SwiftUI上填充图像,如滑块。

问题描述 投票:0回答:1

形象。- > 叶子图像

如何在SwiftUI上填充像滑块一样的图片?

xcode image swiftui mask
1个回答
1
投票

要实现像滑块一样的填充,你可以绘制一个自定义形状。

下面是一个快速演示,你可以做什么

struct Leaf: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: .init(x: rect.minX, y: rect.midY))
            path.addCurve(
                to: .init(x: rect.maxX, y: rect.midY - 20),
                control1: .init(x: rect.midX - rect.maxX / 6, y: rect.minY),
                control2: .init(x: rect.maxX - 20, y: rect.midY - 20)
            )
            path.addCurve(
                to: .init(x: rect.minX, y: rect.midY),
                control1: .init(x: rect.maxX - 20, y: rect.maxY - 20),
                control2: .init(x: rect.midX - 40, y: rect.maxY - 20)
            )
            path.closeSubpath()
        }
    }
}

struct LeafView: View {

    var fillPercentage: CGFloat

    private var animatableData: Double {
        get {
            return Double(fillPercentage)
        }
        set {
            fillPercentage = CGFloat(newValue)
        }
    }

    private func needsToBeFilledWidth(totalWidth: CGFloat) -> CGFloat {
        return totalWidth * (100 - fillPercentage) / 100
    }

    var body: some View {
        GeometryReader { geometry in
            Leaf()
                .foregroundColor(Color.gray.opacity(0.3))
                .frame(width: 200, height: 200)
                .overlay(
                    Rectangle()
                        .foregroundColor(Color.green)
                        .offset(x: -self.needsToBeFilledWidth(totalWidth: geometry.size.width))
                        .clipShape(Leaf())
                )

        }
    }
}

struct Demo: View {

    @State var percentage: CGFloat = 0

    var body: some View {
        VStack {

            LeafView(fillPercentage: percentage)
                .frame(width: 200, height: 200)

            Slider(value: $percentage, in: 0...100)

        }.padding()
    }
}

结果

enter image description here

详见: 你可以调查我的小库显示它是如何实现的。

© www.soinside.com 2019 - 2024. All rights reserved.