Zoom issue with UIImageView - iphone

I am trying to get pinch/zoom work but to no luck... please check code attached any help is appreciated.
#import "SlideShowViewController.h"
#import "SomAppDelegate.h"
#import "MainCategory.h"
#import <sqlite3.h>
#import "UIImage+Resizing.h"
NSInteger Val;
NSInteger AIX;
NSInteger AIY;
NSInteger Height;
NSInteger Pre;
NSInteger Valtab;
NSInteger ImageVal;
NSInteger ValScroll;
UIToolbar *tabBar;
UIActivityIndicatorView *activityIndicator;
UIActivityIndicatorView *activityIndicator1;
#class SomAppDelegate;
#class SlideShowViewController;
#interface SlideShowView : UIView<UIScrollViewDelegate>
{
NSArray * mImages;
UIImageView * mLeftImageView;
UIImageView * mCurrentImageView;
UIImageView * mRightImageView;
NSUInteger mCurrentImage;
BOOL mSwiping;
UIImageView * result;
NSString *imageName;
CGFloat mSwipeStart;
UIScrollView *NewView;
NSTimer *timer;
//////////////////////////////////////////////////////for pinch and Zoom//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CGPoint gestureStartPoint;
CGPoint wmsImageViewCenter;
double unitDistance;
double initialDistance;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
#property (nonatomic, retain)UIView *NewView;
- (double)getDistance:(CGPoint)fromPoint toPoint:(CGPoint)otherPoint;
-(id)initWithImages:(NSArray *)inImages;
#end
#interface SlideShowView(PrivateMethods)
-(UIImageView *)newPieceViewWithImageNamed:(NSString *)imageName atPostion:(CGPoint)centerPoint;
- (void)animateFirstTouch:(double)scale;
#end
#pragma mark -
#implementation SlideShowView
#synthesize NewView;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImage *pigImage1 =[UIImage imageWithContentsOfFile:[mImages objectAtIndex:inImageIndex]];
result=[[UIImageView alloc] initWithImage:pigImage1];
pigImage1=nil;
[pigImage1 release];
result.opaque = YES;
CGRect frameRect = [result frame];
unitDistance = [self getDistance:CGPointMake(0, 0) toPoint:CGPointMake(frameRect.size.width, frameRect.size.height)] / 4.0;
result.userInteractionEnabled =NO;
result.alpha = 1.0;
result.backgroundColor = [UIColor blackColor];
result.contentMode = UIViewContentModeScaleAspectFit;
result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return result;
}
-(UIImage*)createImage:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImage *pigImage1 =[UIImage imageWithContentsOfFile:[mImages objectAtIndex:inImageIndex]];
return pigImage1;
}
- (id)initWithImages:(NSArray *)inImages
{
initialDistance = 1;
unitDistance = 1;
[self setMultipleTouchEnabled:YES];
self.multipleTouchEnabled = YES;
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount=[inImages count];
ImageVal=imageCount;
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
result=nil;
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
result=nil;
}
}
self.opaque = YES;
self.backgroundColor = [UIColor blackColor];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[mImages release];
[result release];
result.image=nil;
result=nil;
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)layoutSubviews
{
if (mSwiping)
return;
CGSize contentSize =self.frame.size; //self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//////////////////////////////////////////// code by pinch and zoom ////////////////////////////////////////////////////////////////
if (mCurrentImageView != nil)
{
if ([touches count] > 1) {
NSArray *touchArray = [touches allObjects];
CGPoint p1 = [[touchArray objectAtIndex:0] locationInView:self];
CGPoint p2 = [[touchArray objectAtIndex:1] locationInView:self];
initialDistance = [self getDistance:p1 toPoint:p2];
}
else
{
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
wmsImageViewCenter = mCurrentImageView.center;
}
}
//////////////////////////////////////// code by rajeev ////////////////////////////////////////////////////////////////
if ([touches count] != 1)
return;
mSwipeStart = [[touches anyObject] locationInView:self].x;
mSwiping = YES;
mLeftImageView.hidden = NO;
mCurrentImageView.hidden = NO;
mRightImageView.hidden = NO;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGSize contentSize =self.frame.size;
///////////////////////////////////////////////////for pinch and zoom/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (mCurrentImageView != nil)
{
if ([touches count] > 1)
{
NSArray *touchArray = [touches allObjects];
CGPoint p1 = [[touchArray objectAtIndex:0] locationInView:self];
CGPoint p2 = [[touchArray objectAtIndex:1] locationInView:self];
float distanceNew = [self getDistance:p1 toPoint:p2];
float dx = (distanceNew - initialDistance)/unitDistance;
double scale = fabs(mCurrentImageView.transform.a + dx);
[self animateFirstTouch:scale];
initialDistance = distanceNew;
}
else if([touches count]==1)
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self];
CGFloat deltaX = gestureStartPoint.x - currentPosition.x;
CGFloat deltaY = gestureStartPoint.y - currentPosition.y;
mCurrentImageView.center = CGPointMake(wmsImageViewCenter.x - deltaX, wmsImageViewCenter.y - deltaY);
mCurrentImageView.opaque = YES;
mCurrentImageView.contentMode = UIViewContentModeScaleAspectFit;
mCurrentImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
}
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CGRect frameRect = [mCurrentImageView frame];
if(frameRect.size.height>Height)
{
contentSize.width=frameRect.size.width;
contentSize.height= frameRect.size.height;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
else
{
if (! mSwiping || [touches count] != 1)
return;
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
mLeftImageView.frame = CGRectMake(swipeDistance - contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(swipeDistance,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(swipeDistance + contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping)
return;
CGSize contentSize = self.frame.size;
NSUInteger count = [mImages count];
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
CGRect frameRect = [mCurrentImageView frame];
if(frameRect.size.height>Height)
{
if (mCurrentImage > 0 && swipeDistance > 250.0f)
{
[mRightImageView removeFromSuperview];
mRightImageView.image=nil;
mRightImageView=nil;
result.image=nil;
result=nil;
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
result=nil;
}
else
{
mLeftImageView = nil;
result=nil;
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
//////////////////////////////////////////////////////////right Swaping ///////////////////////////////////////////////////////////////////////
else if (mCurrentImage < count - 1 && swipeDistance < -250.0f)
{
[mLeftImageView removeFromSuperview];
mLeftImageView.image=nil;
mLeftImageView=nil;
result.image=nil;
result=nil;
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
result=nil;
}
else
{
mRightImageView=nil;
result=nil;
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
}
else
{
///////////////////////////////////////////////////// Left swaping////////////////////////////////////////////////////////////////////////////
if (mCurrentImage > 0 && swipeDistance > 50.0f)
{
[mRightImageView removeFromSuperview];
mRightImageView.image=nil;
mRightImageView=nil;
result.image=nil;
result=nil;
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
result=nil;
}
else
{
mLeftImageView = nil;
result=nil;
}
}
//////////////////////////////////////////////////////////right Swaping ///////////////////////////////////////////////////////////////////////
else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
{
[mLeftImageView removeFromSuperview];
mLeftImageView.image=nil;
mLeftImageView=nil;
result.image=nil;
result=nil;
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
result=nil;
}
else
{
mRightImageView=nil;
result=nil;
}
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f,0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
}
///////////////////////////////////////////////////////////////////////////////////Tab Bar functionality /////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark === Animating subviews ===
#pragma mark
- (void)animateFirstTouch:(double)scale
{
if (mCurrentImageView != nil)
{
CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
mCurrentImageView.transform = transform;
/*
CGSize contentSize = self.frame.size;
if(contentSize.width>1024)
{
//contentSize= CGSizeMake(1024, 1024);
mCurrentImageView.opaque = YES;
mCurrentImageView.contentMode = UIViewContentModeScaleAspectFit;
mCurrentImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
mCurrentImageView.clipsToBounds = YES;
//mCurrentImageView.frame = self.bounds;
[mCurrentImageView setNeedsLayout];
}
*/
}
}
- (double)getDistance:(CGPoint)fromPoint toPoint:(CGPoint)otherPoint
{
double deltaX = otherPoint.x - fromPoint.x;
double deltaY = otherPoint.y - fromPoint.y;
return sqrt(pow(deltaX, 2) + pow(deltaY, 2));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SlideShowView
#implementation SlideShowViewController
#synthesize Values,PreVal;
#synthesize ImageID,ImagePath,ImagePos,CatID,SlideID,CID;
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
int counter=0;
ImageID=[[NSMutableArray alloc]init];
ImagePath=[[NSMutableArray alloc]init];
ImagePos=[[NSMutableArray alloc] init];
CatID=[[NSMutableArray alloc] init];
SlideID=[[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"Category.sqlite3"];
sqlite3 *db;
if (sqlite3_open([writablePath UTF8String], &db) == SQLITE_OK)
{
sqlite3_stmt *statement = nil;
NSString *insertQuery=[NSString stringWithFormat:#"select *from Image where SlideID=%d and CatID=%d;",Values,CID];
const char *sql = [insertQuery cStringUsingEncoding:NSASCIIStringEncoding];
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSAssert1(0,#"error1",sqlite3_errmsg(db));
}
else
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
counter++;
[ImageID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,0)]];
[ImagePath addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,1)]];
[ImagePos addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,2)]];
[CatID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,3)]];
[SlideID addObject:[NSString stringWithFormat:#"%s",(char *)sqlite3_column_text(statement,4)]];
}
sqlite3_finalize(statement);
}
}
sqlite3_close(db);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Slide= [[[SlideShowView alloc] initWithImages:ImagePath] autorelease];
self.view=Slide;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
tabBar.alpha = 0.0;
if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
{ AIX=510;
AIY=360;
Valtab=690;
ValScroll=730.0;
Height=1008;
}
else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight)
{
AIX=510;
AIY=360;
Valtab=690;
ValScroll=730.0;
Height=750;
}
else if(interfaceOrientation == UIInterfaceOrientationPortrait)
{
AIX=360;
AIY=510;
Valtab=945;
ValScroll=530;
Height=1008;
}
else
{
AIX=360;
AIY=510;
Valtab=945;
ValScroll=530.0;
Height=750;
}
return YES; //(interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
- (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.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[super dealloc];
[activityIndicator release];
}
#end

Try rearranging your init method a little:
- (id)initWithImages:(NSArray *)inImages
{
initialDistance = 1;
unitDistance = 1;
// remove these
// [self setMultipleTouchEnabled:YES];
// self.multipleTouchEnabled = YES;
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount=[inImages count];
ImageVal=imageCount;
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
result=nil;
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
result=nil;
}
}
self.opaque = YES;
self.backgroundColor = [UIColor blackColor];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// move to here after the init on super is done
self.multipleTouchEnabled = YES;
}
return self;
}
Calling init on the super probably undoes your efforts to set it beforehand.

Related

How to increase the size and height of view by dragging the view from the corners in UITapGestureRecognizer in iphone?

I am doing the project in which I have to show one Image, when I click on the image one "white view "will come on the upper side of the image. And when I double click on the "two pins" will come out on the "white view". When I pull these two pins the width and height of the white view increase and decrease.
I am not able to do this.
Any Idea from experts would be highly welcome.
Second_View.h file
#import <UIKit/UIKit.h>
#interface Second_View : UIViewController<UIGestureRecognizerDelegate>{
UITapGestureRecognizer *tap;
UISwipeGestureRecognizer *swipe;
UIPanGestureRecognizer *pan;
CGPoint startLocation;
CGFloat lastScale;
CGFloat firstX;
CGFloat firstY;
CGPoint lastLocation;
UIImageView *imageVw;
}
#property (nonatomic) CGPoint center;
#property (nonatomic) NSInteger count;
#property(nonatomic,retain) UIImageView *imageVw;
#end
Second_View.m file
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor grayColor];
imageVw = [[UIImageView alloc]initWithFrame:CGRectMake(200, 200, 500, 400)];
imageVw.image = [UIImage imageNamed:#"redacted2.jpg"];
imageVw.userInteractionEnabled=YES;
imageVw.autoresizesSubviews = YES;
imageVw.alpha = 0.93; // for opacity
[self.view addSubview:imageVw];
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
tap.numberOfTapsRequired = 1;
[imageVw addGestureRecognizer:tap];
tap.delegate=self;
pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(panAction:)];
[pan setMinimumNumberOfTouches:1];
[pan setMaximumNumberOfTouches:2];
[pan setDelegate:self];
count=0;
[imageVw addGestureRecognizer:pan];
}
- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)gestureRecognizer translationInView:self.view];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateBegan) {
firstX = [[gestureRecognizer view] center].x;
firstY = [[gestureRecognizer view] center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[gestureRecognizer view] setCenter:translatedPoint];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateEnded) {
CGFloat velocityX = (0.2*[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:self.view].x);
CGFloat finalX = translatedPoint.x + velocityX;
CGFloat finalY = firstY;// translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
if (finalX < 0) {
//finalX = 0;
} else if (finalX > 768) {
//finalX = 768;
}
if (finalY < 0) {
finalY = 0;
} else if (finalY > 1024) {
finalY = 1024;
}
} else {
if (finalX < 0) {
//finalX = 0;
} else if (finalX > 1024) {
//finalX = 768;
}
if (finalY < 0) {
finalY = 0;
} else if (finalY > 768) {
finalY = 1024;
}
}
}
}
-(void)handleTap:(UIPanGestureRecognizer *)gestureRecognizer
{
CGPoint location = [gestureRecognizer locationInView:gestureRecognizer.view];
NSLog(#"x:%f y:%f",location.x,location.y);
NSArray *subViewsOfImage = [imageVw subviews];
for (id subView in subViewsOfImage) {
CGRect frame1=[subView frame];
int x=0;
int y=0;
x=frame1.origin.x+frame1.size.width;
y=frame1.origin.y+frame1.size.height;
if ((location.x>=frame1.origin.x && location.x<x) && (location.y>=frame1.origin.y && location.y<y) )
{
NSLog(#"No");
return;
}
}
derivedView *view=[[derivedView alloc]initWithFrame:CGRectMake(location.x, location.y, 100, 30)];
[view setBackgroundColor:[UIColor whiteColor]];
[imageVw addSubview: view];
NSArray * subViewsOfImage1 = [imageVw subviews];
NSLog(#"subViewsOfImage = %#",subViewsOfImage1);
NSLog(#"Yes");
}
derivedView.h file
#import <UIKit/UIKit.h>
#interface derivedView : UIView<UIGestureRecognizerDelegate>
{
UIPanGestureRecognizer *pan;
UITapGestureRecognizer *tap1;
UITapGestureRecognizer *tap2;
UITapGestureRecognizer *tap3;
CGPoint lastLocation;
CGFloat firstX;
CGFloat firstY;
UIImageView *rPinImgView;
UIImageView *lPinImgView;
}
#end
derivedView.m file
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(panAction:)];
[pan setDelegate:self];
[self addGestureRecognizer:pan];
tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapAction:)];
[tap1 setDelegate:self];
[self addGestureRecognizer:tap1];
}
return self;
}
- (void)tapAction:(UITapGestureRecognizer *)gestureRecognizer {
// lPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(-15,-20, 30, 30)];
// lPinImgView.image=[UIImage imageNamed:#"pin"];
// // pin.frame=CGRectMake(frame1.origin.x, frame1.origin.y-15, 10, 10);
//
// rPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake (self.frame.size.width-15 ,23, 30, 30)];
// //pin1.frame=CGRectMake(frame1.origin.x+frame1.size.width, frame1.origin.y+5, 10, 10);
// rPinImgView.image=[UIImage imageNamed:#"pin1"];
// [self addSubview:lPinImgView];
// [self addSubview:rPinImgView];
NSArray *subViews=[self subviews];
NSLog(#"subViews%#",subViews);
if ([subViews count]>0) {
[lPinImgView removeFromSuperview];
[rPinImgView removeFromSuperview];
}else
{
lPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(-15,-20, 30, 30)];
lPinImgView.image=[UIImage imageNamed:#"pin"];
// pin.frame=CGRectMake(frame1.origin.x, frame1.origin.y-15, 10, 10);
rPinImgView=[[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width-15 ,23, 30, 30)];
//pin1.frame=CGRectMake(frame1.origin.x+frame1.size.width, frame1.origin.y+5, 10, 10);
rPinImgView.image=[UIImage imageNamed:#"pin1"];
tap2=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector (rPinImageTap:)];
[rPinImgView addGestureRecognizer:tap2];
[tap2 setDelegate:self];
tap3=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(lPinImageTap:)];
[rPinImgView addGestureRecognizer:tap3];
[tap3 setDelegate:self];
[self addSubview:lPinImgView];
[self addSubview:rPinImgView];
}
- (void)lPinImageTap:(UIPanGestureRecognizer *)gestureRecognizer
{
}
- (void)rPinImageTap:(UIPanGestureRecognizer *)gestureRecognizer
{
}
- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)gestureRecognizer translationInView:self];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateBegan) {
firstX = [[gestureRecognizer view] center].x;
firstY = [[gestureRecognizer view] center].y;
}
// translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY);
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[gestureRecognizer view] setCenter:translatedPoint];
if ([(UIPanGestureRecognizer*)gestureRecognizer state] == UIGestureRecognizerStateEnded) {
CGFloat velocityX = (0.2*[(UIPanGestureRecognizer*)gestureRecognizer velocityInView:self].x);
CGFloat finalX = translatedPoint.x + velocityX;
CGFloat finalY = firstY;// translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
if (finalX < 0) {
//finalX = 0;
} else if (finalX > 768) {
//finalX = 768;
}
if (finalY < 0) {
finalY = 0;
} else if (finalY > 1024) {
finalY = 1024;
}
} else {
if (finalX < 0) {
//finalX = 0;
} else if (finalX > 1024) {
//finalX = 768;
}
if (finalY < 0) {
finalY = 0;
} else if (finalY > 768) {
finalY = 1024;
}
}
}
}
}
Have a look at this below link and download the project and check:
https://github.com/spoletto/SPUserResizableView

Draw random design on uiview

I want to draw a random design on uiview just like we are drawing on paint brush I want where user touch on screen start drawing. like if he wants to write ok in it than he can draw it.if he want to make duck or ball so he can make it. plz help me.
Try this.
In this, You will have to use self.view.frame wherever i have myPic.Frame.
In Header File:
#import <Foundation/Foundation.h>
#interface DrawView : UIView {
UIImage *myPic;
NSMutableArray *myDrawing;
}
-(void)drawPic:(UIImage *)thisPic;
-(void)cancelDrawing;
#end
and in Implementation File:
#import "DrawView.h"
#implementation DrawView
-(void)drawPic:(UIImage *)thisPic {
myPic = thisPic;
[myPic retain];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
float newHeight;
float newWidth;
if (!myDrawing) {
myDrawing = [[NSMutableArray alloc] initWithCapacity:0];
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
if (myPic != NULL) {
float ratio = myPic.size.height/460;
if (myPic.size.width/320 > ratio) {
ratio = myPic.size.width/320;
}
newHeight = myPic.size.height/ratio;
newWidth = myPic.size.width/ratio;
[myPic drawInRect:CGRectMake(0,0,newWidth,newHeight)];
}
if ([myDrawing count] > 0) {
CGContextSetLineWidth(ctx, 5);
for (int i = 0 ; i < [myDrawing count] ; i++) {
NSArray *thisArray = [myDrawing objectAtIndex:i];
if ([thisArray count] > 2) {
float thisX = [[thisArray objectAtIndex:0] floatValue];
float thisY = [[thisArray objectAtIndex:1] floatValue];
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, thisX, thisY);
for (int j = 2; j < [thisArray count] ; j+=2) {
thisX = [[thisArray objectAtIndex:j] floatValue];
thisY = [[thisArray objectAtIndex:j+1] floatValue];
CGContextAddLineToPoint(ctx, thisX,thisY);
}
CGContextStrokePath(ctx);
}
}
}
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[myDrawing addObject:[[NSMutableArray alloc] initWithCapacity:4]];
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
[self setNeedsDisplay];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint curPoint = [[touches anyObject] locationInView:self];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
[[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
[self setNeedsDisplay];
}
-(void)cancelDrawing {
[myDrawing removeAllObjects];
[self setNeedsDisplay];
}
- (void)dealloc {
[super dealloc];
[myPic release];
[myDrawing release];
}
#end
you will have to make your UIView a subClass of the above. And in your controller class.m file, you'll have to add and call these two methods.
I hope this works.
-(IBAction)clear {
[self.view cancelDrawing];
}
-(IBAction)saveDrawing
{
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finishedPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(finishedPic, self, #selector(exitProg:didFinishSavingWithError:contextInfo:), nil);
}

iPhone - My new view is blocking my toolbar

I have a problem with my app. With help by a tutorial I've created a slideshow with pictures. I've added a toolbar so it's possible to go back. The problem is that when the pictures are showing, the toolbar disappear. I've been trying to google the problem and so on, but I can't solve it. In a "previous" class I create SlideShowViewController, and inside that class I have another one called SlideShowView. I hope this ain't to messy or stupid, cause I really need help.
Here is the code:
#import "SlideShowViewController.h"
#import "Pictures.h"
#interface SlideShowView : UIView
{
NSArray * mImages;
UIImageView * mLeftImageView;
UIImageView * mCurrentImageView;
UIImageView * mRightImageView;
NSUInteger mCurrentImage;
Pictures *picRef;
SlideShowViewController *slideRef;
BOOL mSwiping;
CGFloat mSwipeStart;
}
- (id)initWithImages:(NSArray *)inImages;
#end // SlideShowView
#pragma mark -
//#import "SlideShowViewController.h"
#implementation SlideShowView
- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImageView * result = [[UIImageView alloc] initWithImage:[mImages objectAtIndex:inImageIndex]];
result.opaque = YES;
result.userInteractionEnabled = NO;
result.backgroundColor = [UIColor whiteColor];
result.contentMode = UIViewContentModeScaleAspectFit;
result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return result;
}
- (id)initWithImages:(NSArray *)inImages
{
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount = [inImages count];
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
}
}
self.opaque = YES;
self.backgroundColor = [UIColor whiteColor];
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
return self;
}
- (void)dealloc
{
[mImages release];
[super dealloc];
}
- (void)layoutSubviews
{
if (mSwiping)
return;
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count] != 1){
return;
}
mSwipeStart = [[touches anyObject] locationInView:self].x;
mSwiping = YES;
mLeftImageView.hidden = NO;
mCurrentImageView.hidden = NO;
mRightImageView.hidden = NO;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping || [touches count] != 1)
return;
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(swipeDistance - contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(swipeDistance, 0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(swipeDistance + contentSize.width, 0.0f, contentSize.width, contentSize.height);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping)
return;
CGSize contentSize = self.frame.size;
NSUInteger count = [mImages count];
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
if (mCurrentImage > 0 && swipeDistance > 50.0f)
{
[mRightImageView removeFromSuperview];
[mRightImageView release];
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
}
else
{
mLeftImageView = nil;
}
}
else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
{
[mLeftImageView removeFromSuperview];
[mLeftImageView release];
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
}
else
{
mRightImageView = nil;
}
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
mLeftImageView.frame = CGRectMake(-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, contentSize.width, contentSize.height);
mRightImageView.frame = CGRectMake(contentSize.width, 0.0f, contentSize.width, contentSize.height);
[UIView commitAnimations];
mSwiping = NO;
}
#end // SlideShowView
#pragma mark -
#implementation SlideShowViewController
#synthesize toolbar;
-(IBAction) goBack:(id) sender{
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
- (id)init
{
if (self = [super initWithNibName:nil bundle:nil])
{
NSArray * images = [NSArray arrayWithObjects:[UIImage imageNamed:#"bifColor.png"],
[UIImage imageNamed:#"DSCF1600.jpg"],
[UIImage imageNamed:#"refresh.png"],
[UIImage imageNamed:#"DSCF1601.jpg"], nil];
self.view = [[[SlideShowView alloc] initWithImages:images] autorelease];
}
return self;
}
#end
Instead of this:
self.view = [[[SlideShowView alloc] initWithImages:images] autorelease];
do that:
UIView* slideShowView = [[[SlideShowView alloc] initWithImages:images] autorelease];
[self.view addSubview:slideShowView];
EDIT: Also don't forget to set the frame of slideShowView!

Xcode: UIScrollView image gallery, having memory problems

I'm Trying to develop an UIScrollView Based Image gallery.
So let me explain what i'm trying to achieve here:
I want to a sliding presentation, that can show upto 140 image. ( You can swipe back and forth )
I've found information on the web, and i've been told the best way to do this is with a UIScrollview which has 3 UIImageViews which you create and remove from superview.
So i managed to create such a "sliding image gallery" with some help from a few tutorials :).
I've managed to upload the application to the ipad, start up the application and run it.
after i viewed about 50-70 slides the app crashes ( out of memory). My knowledge of Obj. C isn't that great .
You'll find the code below: it Prob. has something to do with releasing the images.
Improvements to the code would be really helpful
#import "ParatelPresentationViewController.h"
//Define the UIView ( we need 3 Image Views left, mid right);
#interface SlideShowView : UIView
{
NSArray * mImages;
UIImageView * mLeftImageView;
UIImageView * mCurrentImageView;
UIImageView * mRightImageView;
NSUInteger mCurrentImage;
BOOL mSwiping;
CGFloat mSwipeStart;
}
- (id)initWithImages:(NSArray *)inImages;
#end // SlideShowView
#pragma mark -
#implementation SlideShowView
- (UIImageView *)createImageView:(NSUInteger)inImageIndex
{
if (inImageIndex >= [mImages count])
{
return nil;
}
UIImageView * result = [[UIImageView alloc] initWithImage:[mImages objectAtIndex:inImageIndex]];
result.opaque = YES;
result.userInteractionEnabled = NO;
result.backgroundColor = [UIColor blackColor];
result.contentMode = UIViewContentModeScaleAspectFit;
result.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ;
return result;
}
- (id)initWithImages:(NSArray *)inImages
{
if (self = [super initWithFrame:CGRectZero])
{
mImages = [inImages retain];
NSUInteger imageCount = [inImages count];
NSLog(#"hoeveel foto's: %i");
if (imageCount > 0)
{
mCurrentImageView = [self createImageView:0];
[self addSubview:mCurrentImageView];
if (imageCount > 1)
{
mRightImageView = [self createImageView:1];
[self addSubview:mRightImageView];
}
}
self.opaque = YES;
self.backgroundColor = [UIColor blueColor];
self.contentMode = UIViewContentModeScaleAspectFit;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
return self;
}
- (void)dealloc
{
[mImages release];
[super dealloc];
}
- (void)layoutSubviews
{
if (mSwiping)
return;
//CGSize contentSize = self.frame.size; // Enable when you use content.width/height
//self.backgroundColor = [UIColor redColor];
mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);// (-1024, 0.0f, 1024, 748) can be replaced by (-contentSize.width, 0.0f, contentSize.width, contentSize.height);
mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
mRightImageView.frame = CGRectMake(1024, 0.0f, 1024, 748);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count] != 1)
return;
mSwipeStart = [[touches anyObject] locationInView:self].x;
mSwiping = YES;
mLeftImageView.hidden = NO;
mCurrentImageView.hidden = NO;
mRightImageView.hidden = NO;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping || [touches count] != 1)
return;
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
//CGSize contentSize = self.frame.size;
mLeftImageView.frame = CGRectMake(swipeDistance - 1024, 0.0f, 1024, 748);
mCurrentImageView.frame = CGRectMake(swipeDistance, 0.0f, 1024, 748);
mRightImageView.frame = CGRectMake(swipeDistance + 1024, 0.0f, 1024, 748);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (! mSwiping)
return;
//CGSize contentSize = self.frame.size;
NSUInteger count = [mImages count];
CGFloat swipeDistance = [[touches anyObject] locationInView:self].x - mSwipeStart;
if (mCurrentImage > 0 && swipeDistance > 50.0f)
{
mRightImageView.image = nil;
//[mRightImageView.image release];
[mRightImageView removeFromSuperview];
[mRightImageView release];
//mRightImageView = nil;
//NSLog(#"Count of mRight : %i",[mRightImageView retainCount]);
mRightImageView = mCurrentImageView;
mCurrentImageView = mLeftImageView;
mCurrentImage--;
if (mCurrentImage > 0)
{
mLeftImageView = [self createImageView:mCurrentImage - 1];
mLeftImageView.hidden = YES;
[self addSubview:mLeftImageView];
}
else
{
mLeftImageView = nil;
}
}
else if (mCurrentImage < count - 1 && swipeDistance < -50.0f)
{
mLeftImageView.image = nil;
//[mLeftImageView.image release];
[mLeftImageView removeFromSuperview];
[mLeftImageView release];
//mLeftImageView = nil;
mLeftImageView = mCurrentImageView;
mCurrentImageView = mRightImageView;
mCurrentImage++;
if (mCurrentImage < count - 1)
{
mRightImageView = [self createImageView:mCurrentImage + 1];
mRightImageView.hidden = YES;
[self addSubview:mRightImageView];
NSLog(#"Count of mRight : %i",[mRightImageView.image retainCount]);
}
else
{
mRightImageView = nil;
}
}
[UIView beginAnimations:#"swipe" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3f];
mLeftImageView.frame = CGRectMake(-1024, 0.0f, 1024, 748);
mCurrentImageView.frame = CGRectMake(0.0f, 0.0f, 1024, 748);
mRightImageView.frame = CGRectMake(1024, 0.0f, 1024, 748);
[UIView commitAnimations];
mSwiping = NO;
}
#end // SlideShowView
#pragma mark -
#implementation ParatelPresentationViewController
- (id)init
{
if (self = [super initWithNibName:nil bundle:nil])
{
NSMutableArray *Displayimages = [[NSMutableArray alloc]init];
int i;
for(i=0 ; i<139 ; i++) {
NSString *tempString = [NSString stringWithFormat:#"Dia%d", i+1];
NSLog(#"Dia%d.jpg", i+1);
NSString *imageFile = [[NSBundle mainBundle] pathForResource:tempString ofType:#"JPG"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imageFile];
if (fileExists){
[Displayimages addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:tempString ofType:#"JPG"]]];
NSLog(#"img");
}else {
break;
}
}
//NSArray * images = [NSArray arrayWithObjects:[UIImage imageNamed:#"1.jpg"], [UIImage imageNamed:#"2.jpg"], [UIImage imageNamed:#"3.jpg"], [UIImage imageNamed:#"4.jpg"], [UIImage imageNamed:#"5.jpg"], nil];
//NSLog(#"Objects Img = %#", images);
NSLog(#"Images %#",Displayimages);
self.view = [[[SlideShowView alloc] initWithImages:Displayimages] autorelease];
[Displayimages release];
}
return self;
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
//return YES;
return UIInterfaceOrientationIsLandscape (interfaceOrientation);
}
#end
If you would find a solution or tips, all are welcome !
Thanks in advance
kind regards Bart !
You definitely have a memory leak in createImageView:. You will have to change
return result;
to
return [result autorelease];
There might be more leaks, but that's an obvious one.
Johannes

How do I display more than one page from a PDF?

Hello I want to make an application in which I have to display pdffile on iphone screen, which has a functionality of zooming. I have multiple pages of pdffile, but the problem is i can get display only one page.
Here is the code :
/*myView.m*/
#implementation MyView
- (void)configureTiledLayer {
if([global getfirsttime] == 0)
{
[global fetchpageCtr : 1];
[global fetchfirsttime:1];
}
zoom = 1.0f;
tiledLayer = [CATiledLayer layer];
TiledDelegate *delegate = [[TiledDelegate alloc] init];
tiledLayer.delegate = delegate;
// get tiledLayer size
CGRect pageRect = CGPDFPageGetBoxRect(delegate.map, kCGPDFCropBox);
int w = pageRect.size.width;
int h = pageRect.size.height;
NSLog(#"height==%d,weight=%d",h,w);
// get level count
int levels = 1;
while (w > 1 && h > 1) {
levels++;
w = w >> 1;
h = h >> 1;
}
NSLog(#"Layer create");
// set the levels of detail
tiledLayer.levelsOfDetail = levels;
// set the bias for how many 'zoom in' levels there are
tiledLayer.levelsOfDetailBias = 5;
// setup the size and position of the tiled layer
CGFloat width = CGRectGetWidth(pageRect);
CGFloat height = CGRectGetHeight(pageRect);
tiledLayer.bounds = CGRectMake(0.0f, 0.0f, width, height);
CGFloat x = width * tiledLayer.anchorPoint.x;
CGFloat y = -height * tiledLayer.anchorPoint.y;
tiledLayer.position = CGPointMake(x * zoom, y * zoom);
tiledLayer.transform = CATransform3DMakeScale(zoom, zoom, 1.0f);
// transform the super layer so things draw 'right side up'
CATransform3D superTransform = CATransform3DMakeTranslation(0.0f, self.bounds.size.height, 0.0f);
self.layer.transform = CATransform3DScale(superTransform, 1.0, -1.0f, 1.0f);
[self.layer addSublayer:tiledLayer];
[tiledLayer setNeedsDisplay];
moving = NO;
NSLog(#"in layer");
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor blueColor];
[self configureTiledLayer];
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder {
if (self = [super initWithCoder:coder]) {
[self configureTiledLayer];
}
return self;
}
- (void)setZoom:(CGFloat)newZoom {
zoom = newZoom;
tiledLayer.transform = CATransform3DMakeScale(zoom, zoom, 1.0f);
}
- (void)zoomIn {
[self setZoom:zoom * 2.0f];
}
- (void)zoomOut {
[self setZoom:zoom * 0.5f];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(touches.count == 1) {
previousPoint = [[touches anyObject] locationInView:self];
} else if(touches.count == 2) {
// pinch zoom
pinchZoom = YES;
NSArray *touches = [event.allTouches allObjects];
CGPoint pointOne = [[touches objectAtIndex:0] locationInView:self];
CGPoint pointTwo = [[touches objectAtIndex:1] locationInView:self];
previousDistance = sqrt(pow(pointOne.x - pointTwo.x, 2.0f) +
pow(pointOne.y - pointTwo.y, 2.0f));
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(touches.count == 1) {
CGPoint currentPoint = [[touches anyObject] locationInView:self];
CGPoint delta = CGPointMake(currentPoint.x - previousPoint.x, currentPoint.y - previousPoint.y);
tiledLayer.position = CGPointMake(tiledLayer.position.x + delta.x * zoom,
tiledLayer.position.y + delta.y * zoom);
previousPoint = currentPoint;
moving = YES;
} else if(touches.count == 2) {
// pinch zoom stuff
NSArray *touches = [event.allTouches allObjects];
CGPoint pointOne = [[touches objectAtIndex:0] locationInView:self];
CGPoint pointTwo = [[touches objectAtIndex:1] locationInView:self];
CGFloat distance = sqrt(pow(pointOne.x - pointTwo.x, 2.0f) +
pow(pointOne.y - pointTwo.y, 2.0f));
CGFloat newZoom = fabs(zoom + (distance - previousDistance) / previousDistance);
[self setZoom:newZoom];
previousDistance = distance;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if(!moving) {
if(touches.count == 1) {
// realy should recenter on a click but I'm being lazy
if([[touches anyObject] tapCount] == 2) {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self zoomOut];
} else {
[self performSelector:#selector(zoomIn) withObject:nil afterDelay:0.25];
}
}
} else {
moving = NO;
}
}
- (void)dealloc {
[tiledLayer release];
[super dealloc];
}
/*TiledDelegate.m*/
#implementation TiledDelegate
- (CGPDFDocumentRef)sfMuni {
if(NULL == sfMuni) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"Hunting-TrappingSynopsis_0910" ofType:#"pdf"];
NSURL *docURL = [NSURL fileURLWithPath:path];
sfMuni = CGPDFDocumentCreateWithURL((CFURLRef)docURL);
}
return sfMuni;
}
- (CGPDFPageRef)map {
int temppageno = [global getpageCtr];
NSLog(#"page ctr ==%d ",temppageno);
if(NULL == map) {
map = CGPDFDocumentGetPage(self.sfMuni, temppageno);
}
return map;
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
NSLog(#"\ndrawLayer:inContext:");
NSLog(#"ctm = %#", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
NSLog(#"box = %#\n", NSStringFromCGRect(CGContextGetClipBoundingBox(ctx)));
CGContextDrawPDFPage(ctx, self.map);
}
- (void)dealloc {
CGPDFPageRelease(map);
CGPDFDocumentRelease(sfMuni);
[super dealloc];
}
/*TiledLayerAppDelegate*/
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
/*TiledLayerViewController*/
- (void)viewDidLoad
{
l_pagectr = 2;
UIButton *btn1 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btn1.frame = CGRectMake(0,0,70,50);
[btn1 setBackgroundColor: [UIColor whiteColor]];
btn1.exclusiveTouch = YES;
[btn1 setTitle:#"Next" forState:UIControlStateNormal];
[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn1 addTarget:self action:#selector(NextPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
}
-(IBAction)NextPressed : (id)sender
{
[global fetchpageCtr : l_pagectr++];
MyView *myview1=[[MyView alloc]init];
}
#end
Here when I pressed Next button it will have to display me the nest page but will display me the same page.I also get the page referance in "CGPDFPageRef" incremented but not displayed.
Plz help me for this.
Why don't you just use UIWebView? It renders PDF and offers zoom controls. No need to reinvent the wheel. Here is documentation for UIWebView.