gpt4 book ai didi

SwiftUI 我想使用 simultaneousGesture 但也想使用孤立的手势

转载 作者:行者123 更新时间:2023-12-05 06:07:25 24 4
gpt4 key购买 nike

我想同时使用 RotationGesture 和 MagnificationGesture。但是我也单独使用这些手势。这是我的代码。


struct TmpView10: View {
@State private var magnify: CGFloat = 1
@State private var lastMagnify: CGFloat = 1
@State private var angle: Angle = .degrees(.zero)
@State private var lastAngle: Angle = .degrees(.zero)

var body: some View {
VStack () {
ZStack () {
Image("someImage")
.resizable()
.aspectRatio(contentMode: .fit)
.scaleEffect(self.magnify)
.rotationEffect(self.angle)
.gesture(RotationGesture()
.onChanged{ angle in
self.angle = angle + self.lastAngle
}
.onEnded { angle in
self.lastAngle = self.angle
}
)
.simultaneousGesture(MagnificationGesture(minimumScaleDelta: 0.5)
.onChanged{ v in
let delta = v / self.lastMagnify
self.lastMagnify = v
self.magnify *= delta
}
.onEnded{ v in
self.lastMagnify = 1
}
)
.clipShape(Circle())
.overlay(
Circle().stroke(LinearGradient(gradient: Gradient(colors: [.yellow, .red, .purple]), startPoint: .bottomLeading, endPoint: .topTrailing), lineWidth: 5))
}
}
}
}

通过这段代码,我可以同时使用两个手势。但是一旦我只旋转图像,MagnificationGesture 就会停止工作。有什么方法可以同时使用 simultaneousGesture 和单个手势吗?

最佳答案

通过使用 .updating GestureState 围绕 minimumScaleDelta 的使用进行编码似乎可以解决问题。

struct ContentView: View {
@State private var lastMagnify: CGFloat = 1
@State private var lastAngle: Angle = .degrees(.zero)
@GestureState private var magnification: (active: Bool, factor: CGFloat) = (active: false, CGFloat(1))
@GestureState private var angle: Angle = .degrees(.zero)

var rotateAndMagnifyGesture: some Gesture {
let rotate = RotationGesture()
.updating($angle) { (newAngle, gestureState, _) in
gestureState = newAngle
}
.onEnded { angle in
lastAngle += angle
}
let magnify = MagnificationGesture()
.updating($magnification) { (value, gestureState, _) in
gestureState.factor = value

let delta = value / lastMagnify
if abs(1 - delta) > 0.3 {
gestureState.active = true
}
}
.onEnded { value in
lastMagnify *= value
}
return rotate.simultaneously(with: magnify)
}

var body: some View {
VStack () {
ZStack () {
Image(systemName: "diamond")
.resizable()
.rotationEffect((lastAngle + angle))
.scaleEffect(magnification.active ? (magnification.factor * lastMagnify) : lastMagnify)
.aspectRatio(contentMode: .fit)
.gesture(rotateAndMagnifyGesture)
.clipShape(Circle())
.overlay(
Circle().stroke(LinearGradient(gradient: Gradient(colors: [.yellow, .red, .purple]), startPoint: .bottomLeading, endPoint: .topTrailing), lineWidth: 5))
}
}
}

关于SwiftUI 我想使用 simultaneousGesture 但也想使用孤立的手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65437562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com