Isn't there an easy way to pinch to zoom in an image in Swiftui?
The SwiftUI API is pretty unhelpful here: the onChanged gives number relative to start of current zoom gesture and no obvious way within a callback to get the initial value. And there is an onEnded callback but easy to miss/forget.
A work around, add:
@State var lastScaleValue: CGFloat = 1.0
Then in the callback:
.gesture(MagnificationGesture().onChanged { val in
let delta = val / self.lastScaleValue
self.lastScaleValue = val
let newScale = self.scale * delta
//... anything else e.g. clamping the newScale
}.onEnded { val in
// without this the next gesture will be broken
self.lastScaleValue = 1.0
}
where newScale is your own tracking of scale (perhaps state or a binding). If you set your scale directly it will get messed up as on each tick the amount will be relative to previous amount.
pinch to zoom graph chart in the chart frame only SwiftUI
figure it out my self...
.clipped(Rectangle())
simple but it will do that magic.
UIImageView pinch zoom swift
I decided to add the imageView to a UIScrollView. It allows the user to zoom and pan over. Here is the code I used.
in order to set max/min zoom I used :
scrollImg.minimumZoomScale = 1.0
scrollImg.maximumZoomScale = 10.0
here is the rest of the code.
var vWidth = self.view.frame.width
var vHeight = self.view.frame.height
var scrollImg: UIScrollView = UIScrollView()
scrollImg.delegate = self
scrollImg.frame = CGRectMake(0, 0, vWidth!, vHeight!)
scrollImg.backgroundColor = UIColor(red: 90, green: 90, blue: 90, alpha: 0.90)
scrollImg.alwaysBounceVertical = false
scrollImg.alwaysBounceHorizontal = false
scrollImg.showsVerticalScrollIndicator = true
scrollImg.flashScrollIndicators()
scrollImg.minimumZoomScale = 1.0
scrollImg.maximumZoomScale = 10.0
defaultView!.addSubview(scrollImg)
imageView!.layer.cornerRadius = 11.0
imageView!.clipsToBounds = false
scrollImg.addSubview(imageView!)
I also had to add this as well
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
Swift 3 & above function prototype
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.mainImage
}
Related Topics
How to Check Two Instances Are the Same Class/Type in Swift
In Swift 3, What Is a Way to Compare Two Closures
Reference to Property in Closure Requires Explicit 'Self.' to Make Capture Semantics Explicit
Why .Pch File Not Available in Swift
Why Are Doubles Printed Differently in Dictionaries
Swift - Custom Setter on Property
Why Is the Shorthand Argument Name $0 Returning a Tuple of All Parameters
Swift: Failing to Copy Files to a Newly Created Folder
Swift: Setting an Optional Property of a Protocol
How to Use an Nsattributedstring with a Scrollview in Swiftui
Select() from Linq in Swift 3.0
How to Check Is a String or Number
Scanning Real-World Object and Generating 3D Mesh from It
How to Reason When I Have to Choose Between a Class, Struct and Enum in Swift