Swiftui - 仅显示视图的百分比 [英] Swiftui - only show a percentage of a view
问题描述
我有一个 RoundedRectangle
,我的目标是在它上面放置另一个 RoundedRectangle
,这样叠加层就会显示完成百分比".不过,我似乎找不到合适的咒语来做到这一点.
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())
在上面的操场中,如果您查看 1%、2% 甚至 3%,您可以看到红色叠加层超出了左上角和左下角的蓝色背景矩形边界.见下图.
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.
我觉得这不是正确的解决方案,但我也找不到合适的组合(尝试 scaleEffect
,一堆 offset
和 position
数学)来真正做到这一点.
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.
对我来说,就像我上面说的,当值为 0.4
时,感觉叠加层应该能够说只让我最左边的 40% 可见".
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.
谢谢!
推荐答案
这是我处理它的方式,所以我不必管理多个 cornerRadius
.
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)
这篇关于Swiftui - 仅显示视图的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!