Reputation: 10038
I'm currently learning the coordinate system in ios and have encountered the following code
let zoomScaleForHeight = scrollView.bounds.height / imageView.bounds.height
let zoomScaleForWidth = scrollView.bounds.width / imageView.bounds.width
scrollView.minimumZoomScale = min(zoomScaleForHeight, zoomScaleForWidth)
imageView
is a subview of scrollView
.
I'm not exactly sure what is it calculating and how it is calculated. Could someone please clarify the logic behind those three lines of code?
Upvotes: 1
Views: 87
Reputation: 722
The minimumZoomScale
represents the factor of which the image needs to be resized to in order to perfectly fit the screen without cropping any edges. Here is an image that represents the scenario:
The scale is calculated by dividing the width/height of the UIScrollView
by the width/height of the UIImageView
. If we would now multiply the width of the UIImageView
with its scale factor, we would get the same width as the UIScrollView
, which is pretty much what we want to accomplish. The same counts for height.
The reason the min()
function is needed is demonstrated by this image:
In this example, only the scale for the height is applied, the scale for width is not taken into account. By doing that the image fits perfectly in height but not in width. Therefore, both scales have to be calculated and the smaller one is to be used in order the fit the image without cropping the edges.
Upvotes: 3