在 SwiftUI 中拖动后,应用旋转使其先前的偏移居中

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

我想在 swiftUI 中创建一个视图,以便我可以拖动视图并根据其当前偏移量旋转视图。但不幸的是,在平移视图后,当我尝试旋转时,它会以其基本偏移为中心旋转,而不是视图的当前中心。我现在正在寻找一个精确的解决方案,以便视图将从当前中心旋转。 我的代码在这里是为了更好地理解:

struct MyGestureView : View {
    
    @State private var lastOffset : CGSize = .zero
    @State private var offset : CGSize = .zero
    
    @State private var lastRotation : Angle = .zero
    @State private var rotation : Angle = .zero
    
    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .offset(offset)
            .rotationEffect(rotation)
            .gesture(
                DragGesture(minimumDistance: 0)
                    .onChanged({ value in
                        offset.width = lastOffset.width + value.translation.width
                        offset.height = lastOffset.height + value.translation.height
                    })
                    .onEnded({ value in
                        lastOffset = offset
                    })
            )
            .gesture(
                RotationGesture(minimumAngleDelta: Angle.degrees(3))
                    .onChanged({ angle in
                        rotation = lastRotation + angle
                    })
                    .onEnded({ angle in
                        lastRotation = rotation
                    })
            )
    }
}
swift swiftui view rotation drag
1个回答
0
投票

首先旋转视图,不添加任何偏移,以便正确旋转视图。然后你可以添加偏移量,这不会影响旋转。

即交换

rotationEffect

offset
 的顺序:

.rotationEffect(rotation) .offset(offset)
    
© www.soinside.com 2019 - 2024. All rights reserved.