Search code examples
iosswiftimagesdwebimage

What is the correct approach to show the image without distortion in collection view


I have a very fundamental question hence not posting any code.

OverView

I have a collection view which makes use of custom layout which I have written. All this custom layout does is it applies some maths and finds out the optimal number of cells to place on screen based on screen width and tries to round off the additional pixels using padding. As a result most of my cells size vary when the collection view changes its orientation especially on a device like iPad Pro. What I mean is if the cell size is 300 x 300 in portrait it might become 320 x 300 something like that in landscape. (They are not exact values just trying to give an idea)

Every single cell has imageView in it and image needs to be downloaded from server. I am making use of SDWebImage. Images downloaded are way bigger than my cells and I don't want to load such big images into memory, hence I have decided that I'll be resizing the image once it is downloaded before putting it on to SDWebImageCache.

Issue

Now as my cells sizes are changing based on device orientation, in order to make the image look pixel perfect I'll have to resize the image every time device rotates for each cell. But that will lead to bad performance.

Solutions I have figured out

  1. I'll have to cache two images each one for one orientation in SDWeImageCache but thats again will increase memory footprint of the app.

  2. Find the biggest size cell will get among various orientation and resize the image to that size and then use the same image for all the smaller cell size with image view having its mode set to AspectToFit.

Please suggest me what is the correct approach. I don't need the code, just need idea.


Solution

  • Let me know if this is a bad idea, but potential options.

    You could

    1) Get the original image size. Save this.

    func resetImage() {

    2) Determine if picture width > height

    3) If width > height, then you know it is gonna be a longer picture. Determine how long you would like it. Let's say you want the wider pictures about 1/10*Width of a cell

    4) Determine the height of the image accordingly. ((1/10)/widthOfCell)*imageHeight

    5) If (width > height) imageView.frame = CGRect(0, 0, 1/10*widthCell, height)

    6) imageView.contentMode = .ScaleAspectFit, imageView.image = UIImage(named: "awesome")

    7) Possibly save imageView.size to use incase another rotation.

    This allows you to change just the imageView instead of saving the image data, hopefully removing the white space. Comment and lemme see whatcha think.