I'm currently working on a project where on iOS the user needs to be able to tap and drag on a SwiftUI Canvas to pan (via a DragGesture()), but macOS should be able to use two fingers to pan, and I'm not sure how to do that.
I've looked around some, and found a solution that doesn't work, which is to combine a DragGesture with a MagnificationGesture/MagnifyGesture, but it's far from functional.
I've provided some code below for just the macOS part.
import SwiftUI
struct InfiniteCanvasV: View {
@State private var scale: CGFloat = 1.0
@State private var translation: CGSize = .zero
var body: some View {
let gesture = SimultaneousGesture(
MagnificationGesture()
.onChanged { value in
self.scale = value
print("Scaling")
},
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
self.translation = value.translation
print("Translating")
}
)
.onChanged { _ in
print("Gesture changed")
}
return ZStack {
Canvas { context, size in
let scaledSize = CGSize(width: size.width * (scale) * 0.75, height: size.height * (scale) * 0.75)
let xOffset = (size.width - scaledSize.width) / 2
let yOffset = (size.height - scaledSize.height) / 2
let scaledRect = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: scaledSize)
context.stroke(
Path(roundedRect: scaledRect, cornerSize: CGSize(width: 10, height: 10)),
with: .color(.green),
lineWidth: 4
)
}
.gesture(gesture)
.frame(width: 300, height: 200)
.border(Color.blue)
Text("\(scale)")
.allowsHitTesting(false)
}
}
}