Wednesday 4 January 2012

CustomScrollView in iPhone

///ScrollView.h

//
//  ScrollViewExampleViewController.h
//  ScrollViewExample
//
//  Created by Paras on 24/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "DataBin.h"


@class AsyncImageViewiPhone;
@class forsaleview;

@interface ScrollViewExampleViewController : UIViewController<UIScrollViewDelegate,UITextViewDelegate> {
    
    UIScrollView *contentView; 
    UIImageView *imgView;
    int currentPage;
    DataBin *objBean;
    
    UIBarButtonItem *item3;
    NSMutableArray *arr;
    AsyncImageViewiPhone *controller;
    NSMutableArray *viewControllers;
    NSString *pageControlUsed;
   UITextView *txtDesc;
    UILabel *lblpage;
    
    int height;
int width;
    forsaleview *objParent;
    
    IBOutlet UIToolbar *toolBar;
IBOutlet UIBarButtonItem *backBarButton;
IBOutlet UIBarButtonItem *forwardBarButton;
IBOutlet UIBarButtonItem *sharebtn;
IBOutlet UIBarButtonItem *commentbtn;
IBOutlet UIBarButtonItem *descbtn;
    NSString *flagShow;
NSTimer *menuHideTimer;

}
@property (nonatomic, assign) int currentPage;
@property (nonatomic, retain) NSString *flagShow;
 -(void) setBean:(id)sender;
-(void) setParent:(id) obj;
- (void)loadScrollViewWithPage:(int)page;
-(void) unloadImages:(int)page;
-(void)makingViewControllerArray;
-(void) changePageManually;
-(void) setLandscap;
-(void) setPortrait;
-(void) hideMenus;
-(void) showMenus;
-(void) setToolBar;

-(NSString*) trimString:(NSString *)theString;
-(NSString *) removeNull:(NSString *) string;
@end

///ScrollView.m

//
//  ScrollViewExampleViewController.m
//  ScrollViewExample
//
//  Created by Paras on 24/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "AppDelegate.h"
#import "ScrollViewExampleViewController.h"

#import "AsyncImageViewiPhone.h"
#import "DataBin.h"
#import "forsaleview.h"

@implementation ScrollViewExampleViewController
@synthesize currentPage;
@synthesize flagShow;
AppDelegate *appDelegete;

- (id)init {
    if (self == [super init]) self.title = @"Weather Map"; return self;
    }
// Return the UIImageView instance that gets zoomed by the scroller 
/*- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imgView;
}*/
-(void)viewDidLoad
{
        
    [super viewDidLoad];

    txtDesc = [[UITextView alloc] initWithFrame:CGRectMake(10, -200, 300, 60)];
[txtDesc setEditable:FALSE];
txtDesc.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
txtDesc.font = [UIFont fontWithName:@"Helvetica" size:12.0];
txtDesc.textColor = [UIColor whiteColor];
//txtDesc.layer.cornerRadius = 5.0;
//txtDesc.layer.borderWidth = 1.0;
//txtDesc.layer.borderColor = [[UIColor blackColor] CGColor];
lblpage = [[UILabel alloc]init];
[self.view addSubview:txtDesc];
txtDesc.alpha = 0;

        // [appDelegete showLoadingView];

}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view  atScale:(float)scale {
    // perform any post-scaling tasks here like re-centering
}


-(void) setBean:(DataBin *)obj {
objBean = obj;
    NSLog(@">>>>>>  ObjBeaNs ===>> objBean ======>> %@",objBean);
    
}

-(void) setParent:(forsaleview *) obj {
objParent = obj;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];
        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
    // For any other character return TRUE so that the text gets added to the view
    return TRUE;
}

//====
-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"__________________ objBean == >> %@\n\n\n\n\n\n",objBean);
    [self setToolBar];
    for (UIView *view in contentView.subviews) {
[view removeFromSuperview];
}
//    [toolBar setOpaque:TRUE];
[self.navigationController.toolbar setTintColor:[UIColor blackColor]];
[self.view bringSubviewToFront:toolBar];

}
-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    NSLog(@"____________DID APEARE______ objBean == >> %@\n\n\n\n\n\n",objBean);
    
   // [[UIApplication sharedApplication] setStatusBarHidden:FALSE animated:TRUE];
    
    //[self fetchArrayOfBeans];
  //  [self setToolBar];
    if (currentPage != 0) {
currentPage--;
[self changePageManually];
}
    int count = [objParent.arrimgurl count];
if (count-1 != currentPage) {
currentPage++;
[self changePageManually];
}

    //currentPage = [objParent.arr indexOfObject:objBean];
    //[self changePageManually];
    NSLog(@"\n\n................%d",currentPage);
    contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
contentView.maximumZoomScale = 1.0;
contentView.minimumZoomScale = 1.0;
contentView.clipsToBounds = NO;
contentView.scrollEnabled = YES;
// a page is the width of the scroll view
//[contentView setBackgroundColor:[UIColor purpleColor]];
contentView.pagingEnabled = YES;
contentView.showsHorizontalScrollIndicator = YES;
contentView.showsVerticalScrollIndicator = YES;
contentView.delegate = self;
// scroll.showsHorizontalScrollIndicator = YES;
[self.view addSubview:contentView];
    
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    
   // [self.view bringSubviewToFront:toolBar];
    
    
    if ((self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)) {
        [self setLandscap];
        NSLog(@">>>>>>> is landscape");
    }
    else {
        NSLog(@">>>>>>> is portrait");
        [self setPortrait];
    }

    NSLog(@">>>>>>>>>>>>>>>>>>>>> Array count :%d", [objParent.arrimgurl count]);
   // arr=[[NSMutableArray alloc]init];
   // ObjParse = [[Parse alloc]init:arr];

   // [[UIApplication sharedApplication] setStatusBarHidden:FALSE animated:TRUE];
    //DataBin *objbean = (DataBin *)[arr objectAtIndex:currentPage];
    //NSLog(@"********** url: %@,........image: %@,......another:     %@.............%@", objBean.originalsourceurl,objBean.image,objBean.link);
   
  //  [controller loadImageFromURL:[NSURL URLWithString:objBean.image] titel:objBean.title];
       // [appDelegete hideLoadingView];
}

-(void) setLandscap {
width = 480;
height = 300;
[contentView setFrame:CGRectMake(0, 0, 480, 300)];
contentView.contentSize = CGSizeMake(contentView.frame.size.width * [objParent.arrimgurl count], 
contentView.frame.size.height);
txtDesc.frame = CGRectMake(0, 44, width, txtDesc.contentSize.height);
for (UIView *view in contentView.subviews) {
[view removeFromSuperview];
}
[self makingViewControllerArray];
[self changePageManually];
}

-(void) setPortrait {
width = 320;
height = 420;
NSLog(@"\nSet Portrait");
[contentView setFrame:CGRectMake(0, 0, 320, 420)];
contentView.contentSize = CGSizeMake(contentView.frame.size.width * [objParent.arrimgurl count], 
contentView.frame.size.height);
txtDesc.frame = CGRectMake(0, 44, 320, txtDesc.contentSize.height);
for (UIView *view in contentView.subviews) {
[view removeFromSuperview];
}
[self makingViewControllerArray];
[self changePageManually];
}

-(void) hideMenus {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
txtDesc.frame = CGRectMake(0, 0, width, txtDesc.contentSize.height);
[UIView commitAnimations];
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self.navigationController setToolbarHidden:YES animated:YES];
//[toolBar setToolbarHidden:TRUE animated:TRUE];
if([menuHideTimer isValid]) {
[menuHideTimer invalidate];
}
menuHideTimer = nil;
flagShow = @"isHidden";
}

-(void) showMenus {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
txtDesc.frame = CGRectMake(0, 44, width, txtDesc.contentSize.height);
[UIView commitAnimations];
    
[self.navigationController setNavigationBarHidden:NO animated:YES];
[self.navigationController setToolbarHidden:NO animated:YES];
flagShow = @"isShown";
    
    
if(menuHideTimer != nil && [menuHideTimer isValid]) {
[menuHideTimer invalidate];
menuHideTimer = nil;
}
menuHideTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(hideMenus) userInfo:nil repeats:FALSE];
}

-(void) setToolBar {
UIBarButtonItem *flexibleSpaceItem1 = [[[UIBarButtonItem alloc] 
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:NULL] autorelease];
    
UIBarButtonItem *flexibleSpaceItem2 = [[[UIBarButtonItem alloc] 
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:NULL] autorelease];
    
// UIBarButtonItem *flexibleSpaceItem3 = [[[UIBarButtonItem alloc] 
// initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
// target:nil action:NULL] autorelease];
//
// UIBarButtonItem *flexibleSpaceItem4 = [[[UIBarButtonItem alloc] 
// initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
// target:nil action:NULL] autorelease];
//    
//    UIBarButtonItem *flexibleSpaceItem5 = [[[UIBarButtonItem alloc] 
// initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
// target:nil action:NULL] autorelease];

//UIImageView *img1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back.png"]];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickBackBarButton)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"next.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickForwardBarButton)];
        item3 = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@"%d of %d",currentPage+1,[objParent.arrimgurl count]] style:UIBarButtonItemStylePlain target:nil action:nil];
[self setToolbarItems:[NSArray arrayWithObjects:flexibleSpaceItem1,item1,item3,item2,flexibleSpaceItem2,nil]];
}
-(void) onClickHomeButton {
NSLog(@"Home button");
[self.navigationController popViewControllerAnimated:YES];
}

-(IBAction) onClickBackBarButton {
NSLog(@"Back button");
if (currentPage != 0) {
        currentPage--;
[self changePageManually];
}
}

-(IBAction) onClickForwardBarButton {
NSLog(@"forward button");
int count = [objParent.arrimgurl count];
if (count-1 != currentPage) {
currentPage++;
[self changePageManually];
}
}
-(void) hideTxtView {
//NSLog(@"in HideTxtView");
txtDesc.hidden = TRUE;
}

- (void)loadScrollViewWithPage:(int)page {
    if (page < 0) return;
    if (page >= [objParent.arrimgurl count]) return;
// replace the placeholder if necessary
//NSLog(@"array count : %d", [arrData count]);
if (page != 0) {
controller = [viewControllers objectAtIndex:page-1];
if ((NSNull *)controller == [NSNull null]) {
//NSLog(@"\nController NIL found ....");
objBean = (DataBin *)[objParent.arrimgurl objectAtIndex:page-1];
//controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height) object:objBean];
controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height)];
[controller setObject:self];
[controller setBean:objBean];
NSString *imageName, *imagePath, *imageUrl;
            /* if ([objBean.title isEqualToString:@"Vespanomics"]) {
             imageName = [@"Grenade or Aid?" stringByAppendingString:@".png"];
             }
             else {*/
            imageName = [objBean.title stringByAppendingString:@".png"];
            imageUrl = objBean.image;
            // }
//imageName = [objBeanData.title stringByAppendingString:@"iPad.png"];
imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == YES) {
[controller imageFromImagePath:imagePath];
}
else {
// objDetailView.setThumbnail = 1;
                NSLog(@"\n>>>><<<%@",[self removeNull:imageUrl]);
[controller loadImageFromURL:[NSURL URLWithString:[self removeNull:imageUrl]]];
}
[viewControllers replaceObjectAtIndex:page-1 withObject:controller];
[controller release];
objBean = nil;
}
if (nil == controller.superview) {
CGRect frame = contentView.frame;
frame.origin.x = frame.size.width * (page-1);
frame.origin.y = 0;
controller.frame = frame;
[controller removeFromSuperview];
[contentView addSubview:controller];
            
}
}
    controller = [viewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null]) {
objBean = (DataBin *)[objParent.arrimgurl objectAtIndex:page];
    //controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height) object:objBean];
controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height)];
[controller setObject:self];
[controller setBean:objBean];
NSString *imageName, *imagePath, *imageUrl;
        /* if ([objBean.title isEqualToString:@"Vespanomics"]) {
         imageName = [@"Grenade or Aid?" stringByAppendingString:@".png"];
         }
         else {*/
        imageName = [objBean.title stringByAppendingString:@".png"];
        imageUrl = objBean.image;
        // }
//imageName = [objBeanData.title stringByAppendingString:@"iPad.png"];
imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == YES) {
[controller imageFromImagePath:imagePath];
}
else {
// objDetailView.setThumbnail = 1;
            NSLog(@"\n>>>><<<%@",[self removeNull:imageUrl]);
[controller loadImageFromURL:[NSURL URLWithString:[self removeNull:imageUrl]]];
}
        [viewControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
objBean = nil;
    }
if (nil == controller.superview) {
        CGRect frame = contentView.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
controller.frame = frame;
[controller removeFromSuperview];
        [contentView addSubview:controller];
    }
    // mainScrollViewIphone = controller;
if (page != [objParent.arrimgurl count]-1) {
controller = [viewControllers objectAtIndex:page+1];
if ((NSNull *)controller == [NSNull null]) {
objBean = (DataBin *)[objParent.arrimgurl objectAtIndex:page+1];
//controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height) object:objBean];
controller = [[AsyncImageViewiPhone alloc] initWithFrame:CGRectMake(0,0,width,height)];
[controller setObject:self];
[controller setBean:objBean];
NSString *imageName, *imagePath, *imageUrl;
            /* if ([objBean.title isEqualToString:@"Vespanomics"]) {
             imageName = [@"Grenade or Aid?" stringByAppendingString:@".png"];
             }
             else {*/
            imageName = [objBean.title stringByAppendingString:@".png"];
            imageUrl = objBean.image;
            // }
//imageName = [objBeanData.title stringByAppendingString:@"iPad.png"];
imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == YES) {
[controller imageFromImagePath:imagePath];
}
else {
// objDetailView.setThumbnail = 1;
                NSLog(@"\n>>>><<<%@",[self removeNull:imageUrl]);
[controller loadImageFromURL:[NSURL URLWithString:[self removeNull:imageUrl]]];
}
[viewControllers replaceObjectAtIndex:page+1 withObject:controller];
[controller release];
objBean = nil;
}
if (nil == controller.superview) {
CGRect frame = contentView.frame;
frame.origin.x = frame.size.width * (page+1);
frame.origin.y = 0;
controller.frame = frame;
[controller removeFromSuperview];
[contentView addSubview:controller];
}
}
objBean = (DataBin *)[objParent.arrimgurl objectAtIndex:page];
self.title = objBean.title;
/* if (!objBean.description || [objBean.description isEqualToString:NULL]) {
        // NSLog(@">>>>>>>>>>>>>>>> desc is null");
txtDesc.text = @"";
}
else {
txtDesc.text = [NSString stringWithFormat:@"%@",  objBean.strDesc];
}
    
    
*/
if ([flagShow isEqualToString:@"isHidden" ]) {
txtDesc.frame = CGRectMake(0, 0, width, txtDesc.contentSize.height);
}
else {
txtDesc.frame = CGRectMake(0, 44, width, txtDesc.contentSize.height);
}
[self unloadImages:page];
}


-(NSString*) trimString:(NSString *)theString {
NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
return theStringTrimmed;
}

-(NSString *) removeNull:(NSString *) string {    
    
NSRange range = [string rangeOfString:@"null"];
    //NSLog(@"in removeNull : %d  >>>> %@",range.length, string);
if (range.length > 0 || string == nil) {
string = @"";
}
string = [self trimString:string];
return string;
}


-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}


-(void) unloadImages:(int)page {
    
    for (int i = 0; i < [viewControllers count]; i++) {
if (i != page && i != page+1 && i != page-1) {
            controller = [viewControllers objectAtIndex:i];
            
            if ((NSNull *)controller != [NSNull null]) {
                if(controller.connection != nil) {
                    [controller.connection cancel];
                    controller.connection = nil;
                }
[controller removeFromSuperview];
controller = nil;
[viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
}
}
    }
}

#pragma mark -
#pragma mark ScrollView delegate Methods


-(void)makingViewControllerArray {
//NSLog(@"\n makingViewControllerArray current page : %d", currentPage);
//currentPage++;
NSMutableArray *controllers = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < [objParent.arrimgurl count]; i++) {
        [controllers addObject:[NSNull null]];
    }
    viewControllers = controllers;
    [viewControllers retain];
    [controllers release];
item3.title = [NSString stringWithFormat:@"%d of %d",currentPage+1,[objParent.arrimgurl count]];
    [item3 retain];
[self loadScrollViewWithPage:currentPage];
}

-(void) changePageManually {
//NSLog(@"current page number : %d", currentPage);
CGRect frame = contentView.frame;
frame.origin.x = frame.size.width * currentPage;
frame.origin.y = 0;
    item3.title = [NSString stringWithFormat:@"%d of %d",currentPage+1,[objParent.arrimgurl count]];
    [item3 retain];
[contentView scrollRectToVisible:frame animated:NO];
}


- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (![pageControlUsed isEqualToString:@"notpageControlUsed"]) {
//NSLog(@">>>>>>>>>>>>>>>>>>>>> page control used before");
        return;
    }
else {
//NSLog(@"\n>>>>>>>>>>>>>>>>>>>>> page control used");
CGFloat pageWidth = contentView.frame.size.width;
int page;
page = floor((contentView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
currentPage = page;
item3.title = [NSString stringWithFormat:@"%d of %d",currentPage+1,[objParent.arrimgurl count]];
        [item3 retain];
pageControlUsed = @"notpageControlUsed";
//NSLog(@"scrollViewDidScroll current page =>>>>>>>>>%d",currentPage);
[self loadScrollViewWithPage:page];   
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//NSLog(@"\nscrollViewDidEndDecelerating\n");
pageControlUsed = @"notpageControlUsed";
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
//NSLog(@"\nScrollViewDidScroll\n");
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    if(menuHideTimer != nil && [menuHideTimer isValid]) {
[menuHideTimer invalidate];
menuHideTimer = nil;
}
}

//- (void)loadView {
    
  

    
     
  //  [self makingViewControllerArray];
  //  [self changePageManually];
    
   /* contentView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    [contentView setScrollEnabled:YES];
    //[contentView setPagingEnabled:YES];

    
    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objBean.image]]];// imageNamed:@"Red Carpet Vets ? Emmy Nominees With Oscar Nods.png"];
    // tempImageView =[[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objbean.originalsourceurl]]]];
    
    //[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    imgView = [[UIImageView alloc] initWithImage:img];
    [imgView setUserInteractionEnabled:NO];
    // Set up the main scroller
    [contentView setFrame:CGRectMake(0, 44,320, 416)];
    if (img.size.width>img.size.height) {
       // [contentView setFrame:CGRectMake(0, 44, img.size.width, 416)];
            imgView.frame = CGRectMake(0, 0, img.size.width, 460);
            [contentView setContentSize:CGSizeMake(img.size.width,416)];
    }
    else if(img.size.width<img.size.height){
     //   [contentView setFrame:CGRectMake(0, 44,320, img.size.height)];
        imgView.frame = CGRectMake(0, 0, 320,img.size.height);
        [contentView setContentSize:CGSizeMake(320,img.size.height)];
    }
    else{
      //  [contentView setFrame:CGRectMake(0, 44,320, img.size.height)];
        imgView.frame = CGRectMake(0,44, 320,img.size.height);
        [contentView setContentSize:CGSizeMake(320,img.size.height)];
    }

    // contentView.frame = CGRectMake(0, 0, 320, img.size.height);
    
    //    [contentView setScrollsToTop:YES];

    [contentView addSubview:imgView];
    //[imgView release] ;
    [contentView setMaximumZoomScale: 2.0f];
    [contentView setMinimumZoomScale: 0.5f];
    [contentView setDelegate:self];
    self.view = contentView;
    //[contentView release];
    // reduce retain count by one
    // Provide support for auto-rotation and resizing
    contentView.autoresizesSubviews = YES;
    contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight);    

    */
   // arr=[[NSMutableArray alloc]init];
  //  ObjParse = [[Parse alloc]init:arr];
    // Download the 600x405 weather map and load it into the image view 
  //  NSURL *url = [NSURL URLWithString:@"http://image.weather.com/images/maps/current/curwx_600x405.jpg"];
//    //DataBin *objbean = (DataBin *)[arr objectAtIndex:currentPage];
//    NSLog(@"********** url: %@,........image: %@,......another:     %@", objBean.originalsourceurl,objBean.image,objBean.link);
//    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objBean.image]]];// imageNamed:@"Red Carpet Vets ? Emmy Nominees With Oscar Nods.png"];
//
//       // tempImageView =[[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objbean.originalsourceurl]]]];
//
//    //[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//    imgView = [[UIImageView alloc] initWithImage:img];
//    [imgView setUserInteractionEnabled:NO];
//    // Set up the main scroller 
//    contentView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//  //  imgView.frame = CGRectMake(0, 0, 320, img.size.height);
////    contentView.frame = CGRectMake(0, 0, 320, img.size.height);
//    [contentView setScrollEnabled:YES];
////    [contentView setScrollsToTop:YES];
//    [contentView setContentSize:CGSizeMake(320, img.size.height)];
//    [contentView addSubview:imgView];
// //   [imgView release] ;
//    [contentView setMaximumZoomScale: 2.0f];
//    [contentView setMinimumZoomScale: 0.5f];
//    [contentView setDelegate:self];
//    self.view = contentView;
//    [contentView release];
//    // reduce retain count by one
//    // Provide support for auto-rotation and resizing
//    contentView.autoresizesSubviews = YES;
//    contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight);    
//}
// Allow the view to respond to iPhone Orientation changes 
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
-(void) dealloc {
    [imgView release];
    [contentView release];
    [super dealloc] ;
}


/*

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
@end

///AsynchViewiPhone.h







#import <UIKit/UIKit.h>
#import "CustomScrollBarDelegate.h"
@class DataBin;
@class ScrollViewExampleViewController;
@class CustomScrollBar;

@interface AsyncImageViewiPhone : UIView <UIApplicationDelegate, CustomScrollBarDelegate, UIScrollViewDelegate> {
NSURLConnection* connection; 
NSMutableData* data; 
UIImageView *image;
UIImageView* imageView;
UIActivityIndicatorView *scrollingWheel;
DataBin *objBeanData;
int indexPath;
int flagSetThumbnail;
    
    ScrollViewExampleViewController *objParent;
CustomScrollBar *scroller;
CGRect fullFrame;
BOOL flagShow;
float imgWidth, imgHeight;
}

@property (nonatomic, assign) int indexPath;
@property (nonatomic, assign) int flagSetThumbnail;
@property (nonatomic, retain) NSURLConnection *connection;

-(void)loadImageFromURL:(NSURL*)url;
-(void) setObject:(id)sender;
-(UIImage*) image;
-(id) initWithFrame:(CGRect)frame;
- (void)thumbWithSideOfLength:(double)length imageName:(NSString*)strImgName;
-(NSString *)applicationDocumentsDirectory;
-(void) imageFromImagePath : (NSString *) path;
-(void) setBean:(id)sender;
-(void) setViewAnimation:(CGRect)frame;


@end

////AsynchViewiPhone.m


#import "AsyncImageViewiPhone.h"
#import <CFNetwork/CFNetwork.h>
#import "DataBin.h"
#import "forsaleview.h"
#import "ScrollViewExampleViewController.h"
//#import "ZoomView.h"
//#import "DetailView.h"
#import "AppDelegate.h"
#import "CustomScrollBar.h"
//#import "ASIHTTPRequest.h"


@implementation AsyncImageViewiPhone

AppDelegate *appDelegate;

@synthesize indexPath;
@synthesize flagSetThumbnail;
@synthesize connection;

-(void) setObject:(ScrollViewExampleViewController *) obj {
objParent = obj;
}

-(void) setBean:(DataBin *)obj {
objBeanData = obj;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
scroller = [[CustomScrollBar alloc] initWithFrame:frame];
scroller.maximumZoomScale = 4.0;
scroller.minimumZoomScale = 1.0;
scroller.clipsToBounds = YES;
// a page is the width of the scroll view
//scroller.backgroundColor = [UIColor redColor];
scroller.scrollEnabled = YES;
scroller.multipleTouchEnabled = YES;
scroller.userInteractionEnabled = YES;
scroller.showsHorizontalScrollIndicator = YES;
scroller.showsVerticalScrollIndicator = YES;
scroller.scrollsToTop = NO;
scroller.delegate = self;
scroller.del = self;
scroller.contentSize = frame.size;
scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
appDelegate = (AppDelegate *)[AppDelegate sharedAppDelegate];
float x = self.bounds.size.width/2;
float y = (self.bounds.size.height/2)+10;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
[scroller addSubview:scrollingWheel];
[scrollingWheel release];
self.clipsToBounds = YES;
[self addSubview:scroller];
    }
    return self;
}

#pragma mark -
#pragma mark image from document Directory

-(void) imageFromImagePath : (NSString *) path {
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
UIImage *img = [UIImage imageWithContentsOfFile:path];

    if (img != nil) {
        [imageView setBackgroundColor:[UIColor clearColor]];
        fullFrame = imageView.frame;
            
        float expWidth, expHeight, orgWidth, orgHeight;
        
        orgWidth = img.size.width;
        orgHeight = img.size.height;
            NSLog(@">><<<>>><<<>>><<ImagePath0");
        NSLog(@"\n\n......Height==%f,.......Width==%f",orgHeight,orgWidth);
        if (orgWidth < orgHeight) {
            
                NSLog(@">><<<>>><<<>>><<ImagePath1");
            if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight) {
                expWidth = 480;
                expHeight = (orgHeight * expWidth)/orgWidth;
                
                if (expHeight < 300) {
                    expHeight = 300;
                    expWidth = (orgWidth * expHeight)/orgHeight;
                }
            }
            else {
                
                expWidth = 320;
                expHeight = (orgHeight * expWidth)/orgWidth;
                
                if (expHeight < 460) {
                    expHeight = 460;
                    expWidth = (orgWidth * expHeight)/orgHeight;
                }
            }
        }
        else {
                NSLog(@">><<<>>><<<>>><<ImagePath2");
            if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight) {
                expHeight = 300;
                expWidth = (orgWidth * expHeight)/orgHeight;
                
                if (expWidth < 480) {
                    expWidth = 480;
                    expHeight = (orgHeight * expWidth)/orgWidth;
                }
            }
            else {
                expHeight = 420;
                expWidth = (orgWidth * expHeight)/orgHeight;
                
                if (expWidth < 320) {
                    expWidth = 320;
                    expHeight = (orgHeight * expWidth)/orgWidth;
                }
            }
        }
        
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.image = img;
        [scroller addSubview:imageView];
        [imageView release];
        [scroller bringSubviewToFront:scrollingWheel];
        //[self addSubview:scroller];
        
        [imageView setNeedsLayout];
        [imageView setNeedsDisplay];
        
        imgWidth = expWidth;
        imgHeight = expHeight;
        [scrollingWheel stopAnimating];
        
        imageView.frame = CGRectMake(0,0,expWidth,expHeight);
        
        //scroller.frame = CGRectMake(0,0,expWidth,expHeight);
        scroller.contentSize = CGSizeMake(expWidth, expHeight);
    }
    else {
        
    }
//[self performSelector:@selector(hideScrollingWheel) withObject:nil afterDelay:1.0];
}

-(void)hideScrollingWheel {
[scrollingWheel stopAnimating];
}
//
//#pragma mark -
//#pragma mark ASIHTTPRequest delegate methods
//
//- (void)requestDone:(ASIHTTPRequest *)request
//{
//    NSData *data1 = [request responseData];
//    NSString *imageName = [NSString stringWithFormat:@"%@.png", objBeanData.title];
// NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
//
//
// if(data1 != nil) {
// [data1 writeToFile:imagePath atomically:YES];
//
// //UIImageView *tempImage = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imagePath]];
// [self thumbWithSideOfLength:0.0 imageName:imageName];
// }
// else
// [[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
//}
//
//- (void)requestWentWrong:(ASIHTTPRequest *)request
//{
//    NSError *error = [request error];
//    NSLog(@"\nError requestWentWrong : %@",[error description]);
//    [scrollingWheel stopAnimating];
//}
//
//#pragma mark -
//#pragma mark Private methods
//
//- (void)loadImageFromURL:(NSURL *)url
//{
//    [scrollingWheel startAnimating];
//    
//    if (imageView != nil) {
// [imageView removeFromSuperview];
// imageView = nil;
// }
//
// if(url == nil)
// {
// [scrollingWheel stopAnimating];
// }
//    // NSLog(@"\n>>>dataBean LoadURL : %@",url);
//    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
//    [request setDelegate:self];
//    [request setDidFinishSelector:@selector(requestDone:)];
//    [request setDidFailSelector:@selector(requestWentWrong:)];
//    NSOperationQueue *queue = appDelegate.downloadQueue;
//    [queue addOperation:request];
//    [request startAsynchronous];
//    [request release];    
//}


#pragma mark -
#pragma mark image from Url 
- (void)loadImageFromURL:(NSURL*)url {
NSLog(@"\n\n -------- class call");
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection cancel];
[connection release];
connection = nil;
if (data!=nil) { 
[data release];
data = nil;
}
if (imageView != nil) {
[imageView removeFromSuperview];
imageView = nil;
}
if(url == nil)
{
[scrollingWheel stopAnimating];
}
else {
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}

#pragma mark -
#pragma mark methods for connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
data = [[NSMutableData data] retain];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj {
[data appendData:dataObj];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)theConnection {
[connection release];
connection=nil;
    // if ([[self subviews] count]>0) {
    // [[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
    // }
NSString *imageName = [NSString stringWithFormat:@"%@.png", objBeanData.title];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
if(data != nil) {
[data writeToFile:imagePath atomically:YES];
//UIImageView *tempImage = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imagePath]];
[self thumbWithSideOfLength:0.0 imageName:imageName];
}
else
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
}

-(void)connection:(NSURLConnection *)theconnection didFailWithError:(NSError *)error {
NSLog(@"ERROR with theConenction");
[scrollingWheel stopAnimating];
[theconnection release];
[data release];
    
    connection = nil;
    
return;
}

#pragma mark -
#pragma mark make thumbnail image 
- (void)thumbWithSideOfLength:(double)length imageName:(NSString*)strImgName {
    //NSLog(@"\nImageName : %@",strImgName);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPathToThumbImage = [documentsDirectory stringByAppendingPathComponent:strImgName];
UIImage *thumbnail;
UIImage *mainImage = [UIImage imageWithContentsOfFile:fullPathToThumbImage];
UIImageView *mainImageView = [[UIImageView alloc] initWithImage:mainImage];
CGRect clippedRect = CGRectMake(0, 0, mainImage.size.width,  mainImage.size.height);
    
UIGraphicsBeginImageContext(CGSizeMake(mainImage.size.width, mainImage.size.height));
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextClipToRect( currentContext, clippedRect);
CGFloat scaleFactor = 1.0;
//this will automatically scale any CGImage down/up to the required thumbnail side (length) when the CGImage gets drawn into the context on the next line of code
CGContextScaleCTM(currentContext, scaleFactor, scaleFactor);
[mainImageView.layer renderInContext:currentContext];
thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(thumbnail);
[imageData writeToFile:fullPathToThumbImage atomically:YES];
NSString *imageName = [NSString stringWithFormat:@"%@.png", objBeanData.title];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName];
[imagePath retain];
    
[self performSelector:@selector(imageFromImagePath:) withObject:imagePath afterDelay:2.0];
}


#pragma mark -
#pragma mark path for Document Directory 
-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}

- (UIImage*) image {
UIImageView* iv = [[self subviews] objectAtIndex:0];
return [iv image];
}

#pragma mark -
#pragma mark scrollView Delegate Methods

-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imageView;
}

#pragma mark -
#pragma mark Touch Delegate Methods


- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}

- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}

- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 1) {
if ([objParent.flagShow isEqualToString:@"isShown"]) {
[objParent hideMenus];
}
else {
[objParent showMenus];
}
}
if ([touch tapCount] == 2) {
if(flagShow) {
flagShow = FALSE;
[scroller setZoomScale:1.0];
[self setViewAnimation:CGRectMake(0,0,imgWidth,imgHeight)];
} else {
flagShow = TRUE;
[self setViewAnimation:fullFrame];
}
}
   
}

-(void) setViewAnimation:(CGRect)frame {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
imageView.frame = frame;
scroller.contentSize = frame.size;
[UIView commitAnimations];
}

- (void)dealloc {
[super dealloc];
}

@end

//////ScrollView.xib

viewcontroller with create only put it



No comments:

Post a Comment