Display images in ScrollView - ios

I want to display some images in a scroll view, but I am facing some issues.
Here is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
myObject = [[NSMutableArray alloc] init];
[myObject addObject:#"tut_5.jpg"];
[myObject addObject:#"tut_2.jpg"];
[myObject addObject:#"tut_3.jpg"];
[myObject addObject:#"tut_4.jpg"];
pageControlBeingUsed = NO;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHight = screenRect.size.height;
for (int i = 0; i < [myObject count]; i++) {
CGRect frame;
frame.origin.x = self.takeTourScrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.takeTourScrollView.frame.size;
NSString *val = [myObject objectAtIndex:i];
UIImage* theImage = [UIImage imageNamed:val];
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
img.image = theImage;
[self.takeTourScrollView addSubview:img];
}
The first first image seems to be ok.
Then when I swipe left I am getting a blank screen
I swipe left again and then I see my second picture. And it goes like that for all the 4 images.
Any ideas what am I doing wrong ?

There are system components that will give you what you want with much less work and a more refined user experience. Using a UICollectionView is one possibility, as mentioned by Vive in her answer. My suggestion would be a UIPageViewController. There is a sample app called PhotoScroller from Apple that shows how to implement a UI very much like what you describe. Do a search in the Xcode docs for "PhotoScroller" to find it.

I'd advise to use UITableView/UICollectionView for such behaviour. You can set the image in each cell and they'll be reused - it will be much better in terms of memory management.
The tableView will by the way place all elements in proper places (you just need to define the height of the cell or the layout).
It will also properly resize on events (eg phone rotation).
Also, you should try to avoid hardcoding the sizes:
CGRectMake(screenWidth*i,0,185 ,284)
You will fail in case of smaller / bigger devices. It'll be a great pain to maintain the code after some time.
-- edit --
After #Duncan C posted his answer, I've noticed you're looking for a paging system. You can go with building your own solution either on UIPageViewController or on UICollectionView. However you can also use third party libraries, I really enjoy this one: https://www.cocoacontrols.com/controls/bwwalkthrough. It has a support of different animations and does a ton of stuff for you :).

you already set the x position of uiscrollview. do not need to set the x postion of UIImageView.Because you used imageview as a subview of uiimagescrollview.
change this line to
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(screenWidth*i,0,185 ,284)];
with
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,185 ,284)];

Related

Zoom and Pan on a UIPageViewController

I have a simple application which consists of a UITableViewController with cells of Languages. When the user clicks a specific language, it brings up a UIPageViewController to show horizontally, 6 images in a pageView. That part is working really well and the images are loading.
I have implemented this, using this tutorial: http://code.tutsplus.com/tutorials/using-scrollstyle-with-uipageviewcontroller--mobile-13551.
I would like to achieve a zoom and pan functionality within this as well now.
I have zoom working with the following code.
CGFloat scale = pinchRecognizer.scale;
self.pageViewController.view.transform = CGAffineTransformScale(self.pageViewController.view.transform, scale, scale);
pinchRecognizer.scale = 1.0;
The problem is that the zoom is always in the centre of the image with no way to pan around the image like you can in a normal Photo on an iOS device.
I have found lots of good tutorials on how to achieve this, like http://iosdeveloperzone.com/2012/07/07/tutorial-all-about-images-part-2-panning-zooming-with-uiscrollview/ as an example. However, my confusion stems from the very first part.
I am loading my UIPageViewController using a NSArray:
self.modelArray = [NSMutableArray arrayWithObjects:[[ImageModel alloc] initWithImageName:#"3facts-english-page1.jpg"], [[ImageModel alloc] initWithImageName:#"3facts-english-page2.jpg"], [[ImageModel alloc] initWithImageName:#"3facts-english-page3.jpg"], nil];
How to I extract each image into a UIImageView?
I can see that fundamentally, I need to have most of this code to enable the Pan:
UIImage* image = [UIImage imageNamed:#"KinkakuJi"];
self.imageView.image = image;
[self.imageView sizeToFit];
self.scrollView.contentSize = image.size;
In my case however, I'm not loading a single UIImage but rather a NSArray. How do I extract the UIImage from the NSArray to make this pan happen?
Any thoughts on this would really be appreciated.

UIScrollView Lazy Loading Images

My app for the iPhone Contains 170 images. I read them into an array, and in the loop add a picture in the viewfinder, then put the image View as sub view of scroll view.
When running my app uses too much memory 700mb. I tried to reduce the size of the pictures, but it didn't work.
One of my friends said that I should add only images # 1 and # 2. When the user block is scrolled to the picture No. 1, then only show the picture No. 2. Then the picture No. 1 to remove from the image viewer and add the picture No. 3.
He says that in this way I can maintain the normal memory consumption. But I don't understand how to do this?
Could you help with an example? Thanks in advance.
Not using UICollectionView
Here is my code:
- (void)addImageViewToScrollView {
_assetsArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 170; j++) {
[_assetsArray addObject:[UIImage imageNamed:[NSString stringWithFormat:#"%d",j]]];
}
//scrollView add subview ImageView
for (int i = 0; i < [_assetsArray count]; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width *i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
_imageView = [[UIImageView alloc]init];
_imageView.image = [_assetsArray objectAtIndex:i];
_imageView.frame = frame;
[self.scrollView addSubview:_imageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * self.assetsArray.count, self.scrollView.frame.size.height);
}
--
Use a UICollectionViewController to solve this issue.
This way only the cells that are required on screen are loaded and all others images are can be popped from cache when you hit a memory warning.
Collection Views work very similar to table views.
To get the collection view to suit what you're doing you'll need to set the flow layout to horizontal scrolling and set the cell sizes to your view's height and width.
Seems like you are trying to add170images onto UIScrollView using UIImageView. Why not use dedicated UITableView's or UICollectionView's? Object of Reusable Cell is to maintain run-time memory consumption. Let's recap on this,
You have 170 ImageViews (_assetsArray) ; expensive consumption
You have 170 Images
Versus, Using UITableView or UICollectionView
You have 1 ImageView in a Cell with 170 rows
You have DataSource of 170 Images were loaded
Your cell will be re-cycled when it needed to display correspond to DataSource
Also, for supporting the multitude images, there are good libraries to reduce images cache. Try to use SDWebImage or FastImageCache. I personally like FIC but you might need to understand the concept.

iOS Image Viewer: Set Zoomed Image Back when Scrolling

I have a gallery view that I use to, surprise, view images. :) I wanted it to be very similar to the standard iOS photo app with the same basic functionality: scrolling through images that are zoomable. To do this, I use a regular scroll view which I then populate with other scroll views that contain the images. The basic idea is something like this:
And, I do the populating the following way:
for (int i = 0; i < [imageGalleryArray count]; i++)
{
UIScrollView *imageContainer = [[UIScrollView alloc] initWithFrame:CGRectMake((windowSize.width * i), 0.0f, windowSize.width, windowSize.height)];
imageContainer.contentSize = CGSizeMake(windowSize.width, windowSize.height);
imageContainer.showsHorizontalScrollIndicator = NO;
imageContainer.showsVerticalScrollIndicator = NO;
imageContainer.bouncesZoom = YES;
imageContainer.delegate = self;
imageContainer.minimumZoomScale = 1.0f;
imageContainer.maximumZoomScale = 3.0f;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, windowSize.width, windowSize.height)];
imageView.image = [[imageGalleryArray objectAtIndex:i] objectForKey:#"image"];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.tag = IMAGEZOOMVIEW;
imageView.opaque = YES;
[imageContainer addSubview:imageView];
[galleryScrollView addSubview:imageContainer];
// Add it to array for proper removal later
[contentScrollViewSubviewList addObject:imageContainer];
}
Quite simple and it works fine. The only problem arises when I am zoomed into an image and want to scroll to another. The expected behavior in this case would be to set the zoom level of all images back to their original size. I do this in the scrollViewDidEndDecelerating delegate method like so:
if (scrollView.tag == GALLERYSCROLLVIEW)
{
for (int i = 0; i < [contentScrollViewSubviewList count]; i++)
{
[[contentScrollViewSubviewList objectAtIndex:i] setZoomScale:1.0f animated:YES];
}
}
Unfortunately, it does not work (or rather not as intended). I did some poking around and found out that the image does indeed animate back to its original size when it is the active slide. To elaborate: if I zoom into an image and scroll to another, the image stays zoomed in. When I scroll back to it, that is when it zooms back to its original size. I, however, need the image to scale back as soon as I move away from it ().
just like in the iOS image viewer).
Frankly, I do not understand the whole zoom mechanic enough to find out how to do this properly, and the UIScrollView documentation is of no help either. Could someone show me how to solve my problem?

iOS: understanding frame and views

I am working programmatically an application for iOS based on a ViewController. I am trying to do so programmatically as I want to understand the underlying concepts.
I have created a subclass of UIImageView and initialized this using an image. In the initialization method I added also a second UIImageView as I would like to handle the two differently but be part of the same object. Ultimately I would like to be able to scale the object (and hence the 2 UIImages) according to the device screen resolution (e.g. if resolution is low then I will scale the two images by 50%). I want to do this because I would like to be able to implement a zoom in and zoom out feature as well as supporting multiple resolutions and screen layouts.
Additional information:
The two images have different size (500x500 pixels) and (350x350
pixels).
My questions are:
how do I position the second image exactly in the center of the first? (I used the center property of the main UIImage but I think I got it wrong.. I thought that the center was the exact center of the square but either I am using it incorrectly or there is something I am missing)
are there any negative side effects for using this approach (UIView subclass class containing an additional UIView?) (E.g. Is it going to create confusion when applying transformation algorithms? Does it reduce the randering speed? Or more simply is it a bad design pattern?)
I find it difficult to understand the positioning of the second image. See code snipped below, this is what I use:
CGRect innerButtonFrame = CGRectMake(self.center.x/2, self.center.y/2,innerButtonSelectedImage.size.width,innerButtonSelectedImage.size.height);
Taken from:
-(id) initWithImage:(UIImage *)image
{
if(self = [super initWithImage:image]){
//
self.userInteractionEnabled = true;
// Initialize gesture recognizers
UITapGestureRecognizer *tapInView = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapInImageView:)];
[self addGestureRecognizer:tapInView];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressInView:)];
[self addGestureRecognizer:longPress];
// Initialize labels
..
// Inner circle image
innerButtonView = [[UIImageView alloc] init];
innerButtonSelectedImage = [UIImage imageNamed:#"inner circle.png"];
CGRect innerButtonFrame = CGRectMake(self.center.x/2, self.center.y/2,innerButtonSelectedImage.size.width,innerButtonSelectedImage.size.height);
innerButtonView.frame = innerButtonFrame;
[innerButtonView setImage:innerButtonSelectedImage];
// Add additional ui components to view
[self addSubview:innerButtonView];
..
[self addSubview:descriptionLabel];
}
return self;
}
EDIT: This is how it looks like if I change the positioning code to the following:
CGRect innerButtonFrame = CGRectMake(0, 0,innerButtonSelectedImage.size.width,innerButtonSelectedImage.size.height);
innerButtonView.frame = innerButtonFrame;
I also don't understand why the image is bigger than the screen.. as the blue one should be 500x500 pixel wide and the screen of the iPhone 6 should be 1334 x 750.
How about:
CGRect innerButtonFrame = CGRectMake(0, 0, innerButtonSelectedImage.size.width,innerButtonSelectedImage.size.height);
innerButtonFrame.center = self.center;
If you need 500*500 circle then add the circle half means Replace 500*500 with 250*250 . And small circle replace 350*350 with 175*175 And solve your problem.
I hope your problem will solve..Enjoy
Thanks..

Is UIView being displayed?

I have a UIViewController. The root UIView contains a custom UIScrollView I'm using for displaying thumbnail images in a grid (ThumbnailGrid class). This grid can contain a lot of UIViews which display images (GridTile class). Because there are so many grid tiles, the user can scroll down the ThumbnailGrid. I want to only load images for grid tiles which the user can actually see, I don't want to load ones for grid tiles which are off the edges of the screen.
How do I determine whether or not one of these GridTile UIViews is being displayed on the screen or not?
I've tried the following but it always seems to return false.
- (bool) isViewDisplayed:(UIView*)view
{
CGRect viewFrame = view.frame;
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
if (CGRectIntersectsRect(viewFrame, appFrame)) return true;
return false;
}
Am I missing something?
Thanks in advance for any help!
EDIT
THE SOLUTION
Turns out the coordinate systems were wrong, so I was getting some strange occurrences where the method should have returned true and instead it returned false, and vice versa.
- (bool) isViewDisplated:(UIView*)view
{
CGRect viewFrame = [parentOfView convertRect:view.frame toView:nil];
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
if (CGRectIntersectsRect(viewFrame, appFrame)) return true;
return false;
}
You also need to convert rect to the correct coordinate system:
- (bool)isViewDisplayed:(UIView*)view
{
if (view.window) {
CGRect viewFrame = [view.window convertRect:view.frame fromView:view.superview];
CGRect screenFrame = view.window.bounds;
return CGRectIntersectsRect(viewFrame, screenFrame);
}
return false;
}
I know it doesn't directly answer your question, but still: why don't you use a UICollectionView? It's able to handle most of the heavy parts for you. You don't have to care about the ones they are outside of the screen. You just to care about the behavior (delegation) and the content (data source).
Honestly, I think you are going about this the wrong way. There are a ton of existing frameworks designed to do exactly this. I don't know if I would spend the time to hand roll my own solution and handle all of the memory and view management. Check out this post: Grid of images in iOS
You could do a compare like this:
NSMutableArray *outArray = [NSMutableArray array];
NSMutableArray *inArray = [NSMutableArray array];
for (UIView *vw in rootView.subViews){
if(vw.frame.origin.x <0 || vw.framew.origin.x >rootView.frame.size.width){
[outArray addObject:vw];
}else if(vw.frame.origin.y <0 || vw.framew.origin.y >rootView.frame.size.height){
[outArray addObject:vw];
}else{
[inArray addObject:vw];
}
}
So in the end your outArray will contain all the views which are partially/fully out of super view and inArray will have all those views which is completely inside the super view.
If you want to check for a single view using a method (say -(bool)isViewDisplayed:(UIView*)vw ), the same code inside the for loop would suffice, only thing is you would have to return true/false instead of adding to an array
PS: If you want to get only views completely out of your super view then instead of comparing against zero check against -vw.frame.size.width & -vw.frame.size.height.
Make use of tags pretty easy to manage.
something like this
UIView *view1 = [UIView]alloc]init];
view1.tag = 1;
[mainView addSubview:view1
];
and to check
UIView *temp = [mainView.view viewWithTag:1];
if(temp!=nil)return YES;
else NO;
see if this helps

Resources