0

Libraries like SDWebImage and AFNetworking add the ability to set the image on a UIImageView based on a URL which loads asynchronously, thus not making the user wait while the image loads.

For my use, I'm creating a gallery similar to Photos.app but the images are loaded from URLs. In case the gallery has say, 50 high resolution images I don't want the user to have to wait for every single one to load before they can view even the first, so these libraries are perfect for my use case (I'll load the first image then load on demand).

However, I'm confused as to how to show the images in the view when their frame is not yet known as the image has yet to be downloaded. This would be a non-issue if every one had the same frame (if they were avatars, for example), but this is not the case.

In my case, I use UIImageViews as follows:

// Create image view
self.imageView = [[UIImageView alloc] initWithImage:image];
self.imageView.userInteractionEnabled = YES;

// Create scroll view
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
self.scrollView.delegate = self;
self.scrollView.contentSize = self.imageView.bounds.size;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.showsVerticalScrollIndicator = NO;
self.scrollView.decelerationRate = UIScrollViewDecelerationRateFast;

// Figure out the zoom extremities, as well as the initial zoom level so full image is visible
CGFloat scrollViewWidthRatio = CGRectGetWidth(self.scrollView.bounds) / self.scrollView.contentSize.width;
CGFloat scrollViewHeightRatio = CGRectGetHeight(self.scrollView.bounds) / self.scrollView.contentSize.height;
CGFloat minScale = MIN(scrollViewWidthRatio, scrollViewHeightRatio);
self.scrollView.minimumZoomScale = minScale;
self.scrollView.zoomScale = minScale;
self.scrollView.maximumZoomScale = 1.0;

// Add image view and scroll view
[self.scrollView addSubview:self.imageView];
[self.view addSubview:self.scrollView];

However this all seems to break when the images load asynchronously. What do I set the frame to as the image could be any of a million different sizes? What do I set the scrollView.contentSize to due to the same issue? How do I calculate the scrollView's zoom scales?

Basically, how do I employ any concept of a frame or sizing when I don't know it yet? Is there a way to refresh all this when the image is loaded?

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

1 Answers1

0

Relayout scrollView all subviews will cost much. The effect you want must be depend on data from Server from which you can get picture size before you have downlaoded. There are many styles, for two main method:

  1. Deal with Url: http://xxx.xx.xx.pic_200*150, 200*150 is picture size
  2. Server return add size data. {@"width":200, @"height":150}

Use the size, you can layout scrollView with default image, then loads asynchronously, and update image when download finish.

Hope can help you!

simalone
  • 2,768
  • 1
  • 15
  • 20