问题
I have a RoundedRectangle, and my objective is to lay another RoundedRectangle over it such that the overlay shows a "percentage complete". I can't seem to find the proper incantation to do so, though.
I think that ideally, the overlay should somehow only show a percentage of itself. Resizing itself to match the percentage skews the shape of the overlay.
import PlaygroundSupport
struct ContentView: View {
@State private var value: Double = 0
var body: some View {
GeometryReader { geom in
VStack {
Slider(value: self.$value, in: 0...1, step: 0.01)
ZStack {
ZStack(alignment: .leading) {
// The main rectangle
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue)
.frame(width: geom.size.width,
height: 200)
// The progress indicator...
RoundedRectangle(cornerRadius: 10)
.fill(Color.red)
.opacity(0.5)
.frame(width: CGFloat(self.value) * geom.size.width,
height: 200)
}
Text("\(Int(self.value * 100)) %")
}
}
}
.padding()
}
}
PlaygroundPage.current.setLiveView(ContentView())
In the above playground, if you look at 1, 2, or even 3 %, you can see that the red overlay is out of the blue background rectangle bounds in the upper and lower left. See image below.
I feel like this is not the proper solution, but I also couldn't find the right mix of things (trying scaleEffect, a bunch of offset and position math) to really nail it.
To me, like I said above, it feels like the overlay should be able to say "only make my left-most 40% visible" when the value is 0.4.
That was long-winded, I apologize for that. If you've read this far, and have any advice to impart, I'd be incredibly appreciative.
Thanks!
回答1:
This how I approach it so I don't have to manage more than one cornerRadius.
VStack {
ZStack(alignment: .leading) {
// The main rectangle
Rectangle()
.fill(Color.blue)
.frame(width: geom.size.width,
height: 200)
// The progress indicator...
Rectangle()
.fill(Color.red)
.opacity(0.5)
.frame(width: CGFloat(self.value) * geom.size.width,
height: 200)
}
.cornerRadius(10)
回答2:
If I correctly understood your concern, here is a solution. Tested with Xcode 11.4 / iOS 13.4.
ZStack {
ZStack(alignment: .leading) {
// The main rectangle
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue)
.frame(width: geom.size.width,
height: 200)
// The progress indicator...
RoundedRectangle(cornerRadius: 10)
.fill(Color.red)
.opacity(0.5)
.frame(width: CGFloat(self.value) * geom.size.width,
height: 200)
}
.clipShape(RoundedRectangle(cornerRadius: 10)) // << here !!
来源:https://stackoverflow.com/questions/62109961/swiftui-only-show-a-percentage-of-a-view