Convert between image (pixels) and scaleAspectFit UIImageView coordinates like a champ!
When working with images in iOS, it's sometimes necessary to convert between an image's pixel coordinates and the coordinates of the UIImageView that displays the image. Here's how to do it.
When working with images in iOS, it's sometimes necessary to convert between an image's pixel coordinates and the coordinates of the UIImageView that displays the image. For example, you might want to know the pixel coordinates of a specific point in the image that the user tapped on, or you might want to highlight a specific area of the image by drawing a rectangle in the UIImageView.
Having a few years of iOS development experience, I thought this would be a somewhat complex matter (ever heard of image scaling? Well, have a look) that I shouldn't just wing it if I didn't want it to come bite me in the buttocks later on, and that there had to be some pretty standard way to deal with it. Oh sweet summer child...
While I did find a library, it is archived and has been abandonned for two years. And the first StackOverflow answer doesn't account for differences in ratios between the image and it's containing UIImageView
when using .scaleAspectFit
scaling. This self-answer had a nice idea, namely using AVMakeRect
to calculate the rect that the image would take up if it were scaled to fit within the UIImageView's bounds while maintaining its aspect ratio. But it could be improved and made both more generic (and thus reusable), and clearer.
So here's what I came up with.