Last active
January 16, 2025 00:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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