Skip to content

Instantly share code, notes, and snippets.

@JacopoMangiavacchi
Created July 31, 2022 22:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacopoMangiavacchi/ac3a5e52ec82fd9c7e445762e7035b59 to your computer and use it in GitHub Desktop.
Save JacopoMangiavacchi/ac3a5e52ec82fd9c7e445762e7035b59 to your computer and use it in GitHub Desktop.
SwiftUI DragGesture & MagnificationGesture
struct DragPinchView: View {
@State var currentOffset = CGSize.zero
@State var currentScale: CGFloat = 1.0
@State var gestureOffset = CGSize.zero
@State var gestureScale: CGFloat = 1.0
var body: some View {
let dragGesture = DragGesture()
.onChanged { value in gestureOffset = value.translation }
.onEnded { _ in
withAnimation {
currentOffset = CGSize(width: gestureOffset.width + currentOffset.width, height: gestureOffset.height + currentOffset.height)
gestureOffset = .zero
}
}
let magnificationGesture = MagnificationGesture()
.onChanged { val in
let delta = val / gestureScale
gestureScale = gestureScale * delta
}
.onEnded { val in
currentScale = gestureScale * currentScale
gestureScale = 1.0
}
GeometryReader { geometry in
VStack {
Circle()
.fill(.red)
.frame(width: 64, height: 64)
.scaleEffect(gestureScale * currentScale)
.offset(CGSize(width: gestureOffset.width + currentOffset.width, height: gestureOffset.height + currentOffset.height))
}
.frame(width: geometry.size.width, height: geometry.size.height)
.background(Color.purple.opacity(0.1))
.gesture(dragGesture)
.gesture(magnificationGesture)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment