Skip to content

Instantly share code, notes, and snippets.

@pitt500
Last active March 16, 2022 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pitt500/472c261ca32bf1feca8dd5b35ecbd376 to your computer and use it in GitHub Desktop.
Save pitt500/472c261ca32bf1feca8dd5b35ecbd376 to your computer and use it in GitHub Desktop.
Magnification gesture demo made in SwiftUI. Check out all the details of this code in this video: https://youtu.be/Gq39U4mJEY4
import SwiftUI
struct ImageDetailView: View {
let image: Image
@State var scale = 1.0
@State private var lastScale = 1.0
private let minScale = 1.0
private let maxScale = 5.0
var magnification: some Gesture {
MagnificationGesture()
.onChanged { state in
adjustScale(from: state)
}
.onEnded { state in
withAnimation {
validateScaleLimits()
}
lastScale = 1.0
}
}
var body: some View {
image
.resizable()
.aspectRatio(contentMode: .fit)
.scaleEffect(scale)
.gesture(magnification)
}
func adjustScale(from state: MagnificationGesture.Value) {
let delta = state / lastScale
scale *= delta
lastScale = state
}
func getMinimumScaleAllowed() -> CGFloat {
return max(scale, minScale)
}
func getMaximumScaleAllowed() -> CGFloat {
return min(scale, maxScale)
}
func validateScaleLimits() {
scale = getMinimumScaleAllowed()
scale = getMaximumScaleAllowed()
}
}
struct ImageDetailView_Previews: PreviewProvider {
static var previews: some View {
ImageDetailView(image: Image(systemName: "applelogo"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment