简体   繁体   English

SwiftUI Rectangle 突然变成 RoundedRectangle

[英]SwiftUI Rectangle suddenly transforms into RoundedRectangle

I have just started learning SwiftUI and was playing around with views and animations, I wanted to make controller kinda like apple has in control center for volume or brightness.我刚刚开始学习 SwiftUI 并且正在玩视图和动画,我想让 controller 有点像苹果在控制中心的音量或亮度。 But i found funny little thing and i don't really know what to do with that.但我发现有趣的小东西,我真的不知道该怎么办。

struct DragControler: View {
    @GestureState var fillPercentGS : Double = 0.5
    @State var fillPercent = 0.5
    var body: some View {
        ZStack{

            Rectangle()
            GeometryReader { geometry in
                VStack(spacing: 0) {
                    Rectangle().foregroundColor(.red) //these rects
                    Rectangle().foregroundColor(.green).frame(height: geometry.size.height * CGFloat(self.fillPercent))
                }.gesture(DragGesture(coordinateSpace: .local).updating(self.$fillPercentGS, body: { (value, state, transaction) in
                    state =  Double(value.location.y/geometry.size.height)

                }).onChanged({ (value) in
                    self.fillPercent = max(0, min(1 - Double(value.location.y/geometry.size.height), 1))
                }))
            }
            Text("\(fillPercent)").foregroundColor(.white)
            }.cornerRadius(50).aspectRatio(1/4, contentMode: .fit).padding()
    }
}

GIF when one of rects fills entire view it becomes rounded GIF 当其中一个矩形填满整个视图时,它会变成圆形

So as you can see on the gif, when i drag it all the way to the top or bottom Rectangles which are clearly said to be Rectangles in code become rounded rectangles因此,正如您在 gif 上看到的那样,当我将它一直拖到顶部或底部时,代码中明确表示为 Rectangles 的 Rectangles 变为圆角矩形

So, why is it happening?那么,为什么会这样呢? I have tried to replace.cornerRadius() modifier with clipShape(RoundedRect(...)) but it doesn't help.我试图用 clipShape(RoundedRect(...)) 替换 .cornerRadius() 修饰符,但它没有帮助。 But it i've found that it helps to explicitly set corner radius of these Rectangles to zero.但我发现它有助于将这些矩形的角半径显式设置为零。

Rectangle().cornerRadius(0).foregroundColor(.red)
Rectangle().cornerRadius(0).foregroundColor(...)

My guess is that it is kinda optimisation swiftUI does on the background我的猜测是 swiftUI 在后台做的有点优化

Thanks in advance提前致谢

It looks like a bug to me, but there is an easy fix.对我来说它看起来像一个错误,但有一个简单的修复。 Simply explicitly set the corner radius of your green rectangle to 0:只需将绿色矩形的角半径显式设置为 0:

Rectangle().foregroundColor(.green).frame(height: geometry.size.height * CGFloat(self.fillPercent)).cornerRadius(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM