Adding number of images on UIScrollView from nsdata - iphone

I have 1000 images in an array in the form of NSData.and I need to show them on scrollview when pushing a view controller.
Currently what I am doing is I am creating image from NSData and add them on scroll view. But it takes long time to push screen from previous screen.
UIImage* img = [UIImage imageWithData:[imageArray objectAtIndex:i]];
The array has NSData for 1000 images, so it takes two much time to get convert it to a uiimage. How can I reduce the time it takes?

May I ask why you don not use a UITableView, it is much more efficient as you can easily recycle cells, and it does the layout for you. I recommend this, loading images on demand, or at least keeping thumbnails in memory and swapping them out for the full size ones. It is not feasible to keep 1000 images in memory if they are larger than a thumbnail.

Alternatively, see Apple's Photoscroller in the developer site: http://developer.apple.com/library/ios/#samplecode/PhotoScroller/Introduction/Intro.html

Have a look at AQGridView. It is deriving from UIScrollView, but has cell-reusing like UITableView.

Related

What is an acceptable FPS for scrolling, and what are tips for improving performance?

I see in many WWDC video's that says you want to achieve 60.0 FPS as close as possible to get a better smooth scrolling experience. I have a UIScrolLView which loads up image and a couple of table view's at once. Currently I am getting 30 FPS. This is half of what the recommended FPS. Just wondering what FPS do you guys typically get for a table view/scroll view that loads up images and other heavy stuff/rendering stuff.
Any other tips for optiziming FPS? I've spend the past week till now firing up Instruments using the time profiler, allocations, and core animation tool to optimize as much as I can.
Just to clarify a bit on what I have. I have a masonry/waterfall/pinterest style layout on the iPad. So it's not just a regular UITableView. It's a UIScrollView that fills out the whole screen, and is filled with a couple of UIView's. Each of this view has a 150x150 UIImageView and a UITableView and also it has some attributed label, drawn using Core Text. So at one glance when you see the screen, you can see 5-8 table view at one shot, each cell again has a UIImageView and then each cell renders attributed label drawn using core text.
So you can just image how deep and complicated this is. This is not just a regular table view with a UIImageView. I know how to get 60 FPS with just one UITableView in an iPhone with a UIImage. The concept is to load images asynchrounously and not to block the main thread as much as possible.
EDIT:
It seems that the problem here is the UITableView that I have inside my view.. when I remove that from the UIView I get really smooth scrolling..
I uploaded a sample project which is a simpler version of what I have, but it clearly shows the problem. The link is here
Many things affect render performance, here are some items you can check:
Profile - You said you already did this, so great job! Unfortunately profiling is often overlooked, even though it can reveal unexpected problems. In one app I was working on a calendar with different cells representing dates. At first scrolling between cells slow, which was unexpected. I thought maybe it was drawing a few cells too many. After profiling I found that [NSCalender currentCalender] was using 85% of my CPU time! After fixing that everything scrolled great!
Images - Large images put a lot of load in CoreGraphics. Scrolling especially requires a lot of draw operations to move them around. One tip is to scale images on the device as little as you can, that makes CoreGraphics' job a lot easier. If an image is twice as large as the view displaying it, resize the UIImage before displaying it in the view. iOS devices handle PNGs best. They are compressed by a tool (pngcrush) at compile time and iOS has special hardware for rendering them.
Edit: JPGs are probably a better option for photos. iOS devices have dedicated JPG decoders as well.
Custom Drawing - If possible, cutback on the amount of custom CGContext drawing you do. Lots of custom drawing has negative effects on animation speed. I would considering using an image over complex custom drawing, if possible.
Cull - Only draw things you need to. UITableView automatically unloads and loads cells as they appear, so this is done for you, but any custom CGContext drawing should only be done when that part is visible. Also automatic view shadows can be very slow in my experience.
Reuse - Use the reuse identifier on UITableView, this will allow UITableView to reuse cell objects rather than reallocating as it scrolls - look at the answer to this question. Also reuse UIImages rather than allocating multiple for the same file. imageNamed caches images automatically but imageFromContents of file does not.
Create your own - You could create your own grid view class that culls it's subviews views hidden off screen, and scrolls with lazy content loading. By writing a custom solution you can fully control the process and create a design optimized for the usage context. For most use cases you will have a hard time building something better than the Apple standard, but I have seen it done in specific cases.
Last resort - Reduce the size of the offending view (improves filtrate), break content into multiple pages, downsize images, cut out older devices that don't perform as well. I would settle for 30 FPS before sacrificing most of that stuff. Devices will continue to get faster, older devices will be eliminated, and your app will gradually get faster.
I get close to 60 fps with my UITableViewController where the table contains about 2000 cells and each cell pulls an image from the web. The trick is to lazy load the images as you need them. This sample code from Apple is pretty helpful.
The general idea is to keep the UI responsive by not blocking the main thread. Perform downloads and other time-consuming tasks on another thread.
I would do something called Lazy Loading, which doesn't load the images until they are actually seen.
Here's a great example on how to do so: http://www.cocoacontrols.com/platforms/ios/controls/mhlazytableimages
Good Luck!
What I've done is to use NSCache. I've created a small class with properties that conforms to the NSCache data protocol (its really easy to do). So what I do is create a relationship between each cell in the main table and various things worth caching: NSAttributed strings, images etc - really anything that takes work to create. I don't preload it but you could.
When you are asked to provide a cell by the tableview, look in your cache for your primary object. If there, pull all all the objects you need. If the cache does not have the object, then get the data the old fashion way, but before you finish, save it in the cache too.
This really helped me reduce "stutter" when scrolling the cell. Also, do NOT animate anything in the cell - that kills performance. Everything should be fully rendered.
Another thing to remember - make sure ever view which can be set to opaque has its property set to YES. That for sure helps the system render the cell (including the backgound view if you use one.)
EDIT:
So you provided information that included UITableViews may the root problem. So two suggestions:
1) Can you step back and figure out how to make the scrollView a single UITableView? With table headers and footers, and section headers and footers, and even the ability to essentially make a cell a floating view, can't you figure out how to rearchitect what you have?
2) So you decide no to suggestion 1. Then, do this. Think of the space used by the tableview as being a container view. Whenever the tableview is edited, take an image snapshot of it and keep this image around. As soon as the user starts to scroll, swap the tableViews out for the images. When the scrollView stops swap the UITableView back in. This of course will take some fine tuning. In fact, you could probably overlay an opaque image snapshot over the table (which will hide it and prevent it from being asked to draw itself) during scrolling.
the human eye sees at about 60 FPS, so that's why it's recommended, but 30 FPS will also appear very smooth, especially when a regular user is viewing it, as opposed to you trying to find as much to fix as possible. This is obviously dependent on how fast the scrolling goes, if the difference from frame to frame is a movement of a few pixels, 30 FPS will do just fine, but faster movement will require a higher FPS to appear smooth
There are a few things you can do in general to get better table view performance:
1) Switch to Loren Brichter's method of drawing UITableViewCell's (for lack of a better link: http://www.therefinedgeek.com.au/index.php/2010/12/21/fast-scrolling-uitableview-updates-for-ios-4-2/)
Basically, all his code does is render all your cell content as one opaque UIView, which UITableView (and CoreGraphics) can very quickly blast onto a UITableViewCell
If you don't want to do all your cell design in drawRect:, you can still use nibs, but:
Make sure every subview is marked opaque
Don't have any transparent/semi-transparent subviews
Don't have any images with an alpha channel != 1.0f.
2) Don't let UIImageView do any scaling to display your image, give it a correctly-sized UIImage
3) If you're using iOS 5 and above, you can register a nib for a particular cell identifier. That way, when you call [tableView dequeueReusableCellWithIdentifier:], you are guaranteed to get a cell. Cell allocation is faster (according to Apple), and you get to write less code:
- (void)viewDidLoad {
UINib *nib = [UINib nibWithNibName:#"MyCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:#"MyCellIdentifier"];
}
// ...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"MyCellIdentifier";
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Commented out code is no longer needed
//if (cell == nil) {
// cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//}
// setup cell
return cell;
}
4) Displaying images downloaded from the web
Display a default image (something to look at while the real image is downloading)
Start the download on a separate thread (hint: use GCD's dispatch_async())
When the image comes in, cache it (hint: NSCache), and display it on the cell
Do all image downloading/caching off the main thread; the only thing you should be doing on the main thread is setting the image (remember UI code HAS to be on the main thread!)
You'll probably want to write an async-capable UIImageView (or use an existing library).
Stay away from EGOImageView, even though it has async downloading, it does cache lookup (which happens to be on disk, so that means costly disk IO) on the main thread before dispatching to a background thread for the download. I used to use it, but I ended up writing my own set of classes to handle this, and it's significantly faster.
-
Just follow these, and stuff other ppl have written here, and you'll have table views that scroll like glass in no time :)
You want 60fps, but 30 fps doesn't look too terrible in actuality. But I would try to achieve 60fps for a smoother look while scrolling.
There are many Performance Improvement possibilities, that are also shown by various tutorials
While 60 FPS is the ideal, games like Halo run very prettily in 30 FPS. The battlefield chaos in Halo probably involve more surprising, rapid motion than most lists, even complex ones like yours!

iPhone - UITableView reload on scrolling

I've a UITableView and each UITableViewCell displays a unique UIImage which is fetched from internet. As we scroll the UITableView, cells are recreated and tableView: cellForRowAtIndexPath: gets called every time to configure cells. So it loads UIImages again and again from internet and scrolling is not smooth.
The solution I found for myself right now is to create NSMutableArray of all those UIImages on ViewDidLoad then load images into UITableViewCells from that NSMutableArray which is for sure giving me smooth scrolling.
My concern with my own solution is that when I keep all UIImages in NSMutableArray and those all objects are kept in memory for as long as application runs, I am most probably making inefficient use of memory.
Is there a better, more efficient way to do this which gives me smooth scrolling as well as best memory usage?
I think this example will help you..
http://kosmaczewski.net/2009/03/08/asynchronous-loading-of-images-in-a-uitableview/
Cache the downloaded images on the filesystem. When loading a cell, first ensure that a cached copy of the associated image is available, then load it using [UIImage imageWithContentsOfFile:].
You should go with array of image link instead of the image.
You should load image asynchronously so that it will improve performance of creation of the UITableviewCell.
Verify that you are using dequeueReusableCellWithIdentifier, it will give you the smoother scrolling.

UIScrollView question... loading images

I have a UIScrollView that does not do paging. I am loading about 500 small (64x64-iPhone 192x192-iPad) images. I do not want to load them all into memory. I would like to load them as the user scrolls.
Can anyone tell me where I can set the images to display? I have an object for each image that holds the image resource name, index number and x and y coordinate where it should be displayed in the UIScrollView. I was hoping there was a method I could override where I could create a UIImageView and then add the view to the scroll view on the fly... maybe preloading 6 to 10 images at a time. Every sample I see uses paging and only displays one image at a time.
Any help or example is greatly appreciated.
Thank you
EDIT:
In the ScrollViewSuite examples from Apple there is a Tiling example. That example has a scrollview that popups up displays images to select from. That is exactly what I am trying to do, but Ineed to load them on the fly. The sample loads all of the thumbnail images into memory. Someone somewhere must be doing this because the iPod/iPhone and iPad do not have alot of memory to load all the images.
Apple has some really good demo code that shows how to do this. Check out TiledScrollView.m especially the layoutSubviews method.
write the code in following method of scrollview:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
I did the same. Load atleast few images in the beginning and then load those images in above method.
PROPERLY ALLOC AND RELEASE IMAGEVIEWS SINCE THEY CAN LEAD TO MEMORY LEAKS
Hope this works for you :)
Cheers :)
Couldn't you just use a UITableView for this?
Edit: Might be worth looking at
u can try making ur tableview horizontal by using CAAffinneTransform and giving the angle as (3.14/2) ie 90 degree annd can have a horizontal tableview with horizontal scroll and can use the above refrence given by MIKE A
regards...

how to add more than 100 uiimageviews in uiscrollview

i have an uiscrollview and i add one by one uiimageviews but when i add more than 40 objects i have problem with memory i guess and the app crashes...what should i do? i am trying to make an app like photo viewer from apple! Help please!
i do not want thumbnais i just want to show the next image when the user flick from one to another but i have to unload the previous image and show the next one
i remove the previous like this
UIImageView l;
l=[[scroll subviews] objectAtIndex:0];
[l removeFromSuperview];
l=nil;
and then i add the next one like this
[scroll insertSubview:imageView atIndex:counter];
but i see a black background no image
please help!
The best way to do this is to load a few of the images at a time into a table view. In each cell of the table, put three thumbnails. You'll need to make a custom cell. That way, the table cells will be de-queued and the memory re-used. Check the Facebook Three20 project, I think they've implemented it like this, so you'll have some code to work with.
http://joehewitt.com/post/the-three20-project/
Ask yourself, do you really need to load all 100 images into memory? Why not just load a few images at a time in the background, depending on what image the user has scrolled to?
Don't do it that way.
If you want to display a 100 small thumbnails, resize them first with core graphics. Then they take up much less memory when you display 100 images at once.
If you want to display a 100 large images but only one is visible at a time, have 1 or 2 image views that load up the current and next images, and animate them in a clever way to make it look an endless stream. You can still use a scrollView, just monitor it's position and position your image views appropriately.
There is exactly an apple sample code that do what you want. Look for the PageControl sample, it is already implemented. Basically the slider gets the image controller from an array of controllers; among other things, when the scroller changes to the previous or next image, controllers are added and removed from this array dynamically to keep memory footprint low.
Have a look at the sample code, it is quite simple.
Hope it helps.

How to implement UIImageView-like delayed loading in UITableView

Background:
I have a UITableView showing an image in each cell. These images are all part of a big pdf-file. So what I am doing is actually rendering little pdf-parts in those UITableViewCells, each cell displaying just one piece. Therefore I add a UIView to the contentview of the cell and render the view on demand.
Rendering these pdf-parts is expensive and each takes about 0.2 seconds (only drawing the Pdf-part), which slows the scrolling of the table terrible down.
Idea:
Now, I know there may be a solution when I look how UIImage renders URL-based images. If you create a UIImage based on a url, these images are rendered somehow delayed. E.g have a look at the iTunes-App.
Smooth scrolling is possible, each image is displayed unrendered and after rendering is finished it appears smoothly.
Problem: How can I render an expensive rendering in a UITableViewCell like described above, by somehow showing the cell delayed? Has anybody an idea, how Apple solved it within UIImageView?
Thanks in advance
Daniel
this is (mostly) duplicate of Lazy load images in UITableViewCell. Check the links and examples there.
In short, what you need is spawning a separate thread for loading the PDF thumbnails, and that thread then signaling back to the main thread with the generated images. This is easily done by using performSelectorInBackground:withObject: and performSelectorOnMainThread:withObject:waitUntilDone: methods.