iOS "View Controller" - iphone

I try to make a game but I have a "warning" that says: "IVBrickerViewController may not respond to -processCollision.
This is the code:
#import "IVBrickerViewController.h"
#implementation IVBrickerViewController
#synthesize scoreLabel;
#synthesize ball;
#synthesize paddle;
#synthesize livesLabel;
#synthesize messageLabel;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void) accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)accel
{
float newX = paddle.center.x + (accel.x *12);
if(newX > 30 && newX <290)
paddle.center = CGPointMake(newX, paddle.center.y);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (isPlaying) {
UITouch *touch = [[event allTouches] anyObject];
touchOffset = paddle.center.x -
[touch locationInView:touch.view].x;
} else {
[self startPlaying];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (isPlaying) {
UITouch *touch = [[event allTouches] anyObject];
float distanceMoved =
([touch locationInView:touch.view].x + touchOffset) -
paddle.center.x;
float newX = paddle.center.x + distanceMoved;
if (newX > 30 && newX < 290)
paddle.center = CGPointMake( newX, paddle.center.y );
if (newX > 290)
paddle.center = CGPointMake( 290, paddle.center.y );
if (newX < 30)
paddle.center = CGPointMake( 30, paddle.center.y );
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self initializeBricks];
[self startPlaying];
}
- (void)initializeBricks
{
brickTypes[0] = #"bricktype1.png";
brickTypes[1] = #"bricktype2.png";
brickTypes[2] = #"bricktype3.png";
brickTypes[3] = #"bricktype4.png";
int count = 0;
for (int y = 0; y < BRICKS_HEIGHT; y++)
{
for (int x = 0; x < BRICKS_WIDTH; x++)
{
UIImage *image = [UIImage imageNamed:
brickTypes[count++ % 4]];
bricks[x][y] = [[[UIImageView alloc] initWithImage:image]
autorelease];
CGRect newFrame = bricks[x][y].frame;
newFrame.origin = CGPointMake(x * 64, (y * 40) + 100);
bricks[x][y].frame = newFrame;
[self.view addSubview:bricks[x][y]];
}
}
}
-(void)startPlaying {
if (!lives) {
lives = 3;
score = 0;
}
UIAccelerometer *theAccel = [UIAccelerometer sharedAccelerometer];
theAccel.updateInterval = 1.0f / 30.0f;
theAccel.delegate = self;
ballMovement = CGPointMake(4, 4);
[self initializeTimer];
scoreLabel.text = [NSString stringWithFormat:#"%05d", score];
livesLabel.text = [NSString stringWithFormat:#"%d", lives];
ball.center = CGPointMake(159, 239);
ballMovement = CGPointMake(4, 4);
// choose whether the ball moves left to right or right or right to left
if (arc4random() % 100 < 50)
ballMovement.x = -ballMovement.x;
messageLabel.hidden = YES;
isPlaying = YES;
[self initializeTimer];
}
-(void)pauseGame {
[theTimer invalidate];
theTimer = nil;
}
-(void)initializeTimer {
if (theTimer == nil) {
float theInterval = 1.0f/30.0f;
//I've renamed animateBall: to gamelogic
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self
selector:#selector(gameLogic) userInfo:nil repeats:YES];
}
}
-(void)gameLogic {
ball.center = CGPointMake(ball.center.x+ballMovement.x,
ball.center.y+ballMovement.y);
BOOL paddleCollision = ball.center.y >= paddle.center.y - 16 &&
ball.center.y <= paddle.center.y + 16 &&
ball.center.x > paddle.center.x - 32 &&
ball.center.x < paddle.center.x + 32;
if(paddleCollision) {
ballMovement.y = -ballMovement.y;
BOOL there_are_solid_bricks = NO;
for (int y = 0; y < BRICKS_HEIGHT; y++)
{
for (int x = 0; x < BRICKS_WIDTH; x++)
{
if (1.0 == bricks[x][y].alpha)
{
there_are_solid_bricks = YES;
if ( CGRectIntersectsRect(ball.frame, bricks[x][y].frame) )
{
[***self processCollision:bricks[x][y]];***
}
}
else
{
if (bricks[x][y].alpha > 0)
bricks[x][y].alpha -= 0.1;
}
}
}
if (!there_are_solid_bricks) {
[theTimer invalidate];
isPlaying = NO;
lives = 0;
messageLabel.text = #"You Win!";
messageLabel.hidden = NO;
}
if (ball.center.y >= paddle.center.y - 16 && ballMovement.y < 0) {
ball.center = CGPointMake(ball.center.x, paddle.center.y - 16);
} else if (ball.center.y <= paddle.center.y + 16 && ballMovement.y > 0) {
ball.center = CGPointMake(ball.center.x, paddle.center.y + 16);
} else if (ball.center.x >= paddle.center.x - 32 && ballMovement.x < 0) {
ball.center = CGPointMake(paddle.center.x - 32, ball.center.y);
} else if (ball.center.x <= paddle.center.x + 32 && ballMovement.x > 0) {
ball.center = CGPointMake(paddle.center.x + 32, ball.center.y);
}
}
if(ball.center.x > 300 || ball.center.x < 20)
ballMovement.x = -ballMovement.x;
if (ball.center.y < 32)
ballMovement.y = -ballMovement.y;
if (ball.center.y > 444) {
[self pauseGame];
isPlaying = NO;
lives--;
livesLabel.text = [NSString stringWithFormat:#"%d", lives];
if (!lives) {
messageLabel.text = #"Game Over";
} else {
messageLabel.text = #"Ball Out of Bounds";
}
messageLabel.hidden = NO;
}
if(ball.center.y > 444 || ball.center.y < 40)
ballMovement.y = -ballMovement.y;
}
- (void)processCollision:(UIImageView *)brick
{
score += 10;
scoreLabel.text = [NSString stringWithFormat:#"%d", score];
if (ballMovement.x > 0 && brick.frame.origin.x - ball.center.x <= 4)
ballMovement.x = -ballMovement.x;
else if (ballMovement.x < 0 && ball.center.x - (brick.frame.origin.x +
brick.frame.size.width) <= 4)
ballMovement.x = -ballMovement.x;
if (ballMovement.y > 0 && brick.frame.origin.y - ball.center.y <= 4)
ballMovement.y = -ballMovement.y;
else if (ballMovement.y < 0 && ball.center.y - (brick.frame.origin.y +
brick.frame.size.height) <= 4)
ballMovement.y = -ballMovement.y;
brick.alpha -= 0.1;
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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 {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[scoreLabel release];
[ball release];
[paddle release];
[livesLabel release];
[messageLabel release];
[super dealloc];
}
#end
I HAVE TWO WARNINGS HERE AT THE #END:
{Incomplete implementation of class 'IVBrickerViewController'}.
{Method definition for'-animateBall:'not found}.
I had changed the .h file from: "-(void)animateBall:(NSTimer *)theTimer;"
to: "-(void)gameLogic:(NSTimer *)theTimer;"
but i get the same warning: "Method definition for'-gameLogic:' not found"
I would like to thank those who have tried to help me.

Make sure that you have
- (void)processCollision:(UIImageView *)brick;
in your IVBrickerViewController.h file.

Problem is in your header file (.h).
There is no correct declaration of processCollision method.
Add it to header file.

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

Paginate carousel item

I have developed a carousel view that looks like the picture in post below
How do I calculate the position of a view animated from a 3-D carousel?
#pragma mark -
#pragma mark - VIEW LIFE CYCLE
- (void)viewDidLoad
{
[super viewDidLoad];
// VIEW FRAME
CGRect Frame = CGRectMake(-40, -40, 80, 80);
// CREATE 6 VIEWS
_CarouselView = [[NSMutableArray alloc] initWithCapacity:6];
int c = 5;
while(c--)
{
UIView *View = [[UIView alloc] initWithFrame:Frame];
View.backgroundColor = [UIColor colorWithRed:(c&4) ? 1.0 : 0.0 green:(c&2) ? 1.0 : 0.0 blue:(c&1) ? 1.0 : 0.0 alpha:1.0];
[_CarouselView addObject:View];
[self.view addSubview:View];
}
_CurrentAngle = _LastAngle = 0.0f;
[self setCarouselAngle:_CurrentAngle];
}
- (void)viewDidUnload
{
}
#pragma mark -
#pragma mark - VIEW TOUCH GESTURE
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(!_TrackingTouch)
{
_TrackingTouch = [touches anyObject];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
_LastAngle = _CurrentAngle;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
// USE MOVEMENT TO DEVICE HOW MUCH TO ROTATE THE CAROUSEL
CGPoint LocationNow = [_TrackingTouch locationInView:self.view];
CGPoint LocationThen = [_TrackingTouch previousLocationInView:self.view];
_LastAngle = _CurrentAngle;
_CurrentAngle += (LocationNow.x - LocationThen.x) * 180.0f / self.view.bounds.size.width;
// the 180.0f / self.view.bounds.size.width just says "let a full width of my view
// be a 180 degree rotation"
// and update the view positions
[self setCarouselAngle:_CurrentAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
_TrackingTouch = nil;
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:#selector(animateAngle) userInfo:nil repeats:YES];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
#pragma mark -
#pragma mark - CAROUSEL ACTIONS
- (void)setCarouselAngle:(float)Angle
{
// ANGLE TO ADD AFTER EACH ELEM
_AngleToAdd = 360.0f / [_CarouselView count];
// APPLY TO ALL VIEWS
for(UIView *View in _CarouselView)
{
float AngleInRadians = Angle * M_PI / 180.0f;
// GET LOCATION
float x = (self.view.bounds.size.width * 0.5f) + 100.0f * sinf(AngleInRadians);
float y = ((self.view.bounds.size.height-200) * 0.5f) + 90.0f * cosf(AngleInRadians);
// ADJUST SCALE BETWEEN 0.75 0.25
float Scale = 0.75f + 0.25f * (cosf(AngleInRadians) + 1.0);
// APPLY TRANSFORMATION
View.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(x, y), Scale, Scale);
// TWEAK ALPHA
View.alpha = 0.1f + 0.5f * (cosf(AngleInRadians) + 1.0);
// SETTING Z POSITION
View.layer.zPosition = Scale;
// GET THE NEXT ANGLE
Angle += _AngleToAdd;
}
}
- (void)animateAngle
{
float AngleNow = _CurrentAngle;
_CurrentAngle += (_CurrentAngle - _LastAngle) * 0.97f;
_LastAngle = AngleNow;
// PUSH THE NEW ANGLE
[self setCarouselAngle:_CurrentAngle];
if(fabsf(_LastAngle - _CurrentAngle) < 0.001)
{
[_AnimationTimer invalidate];
_AnimationTimer = nil;
}
}
Everything works fine but i am having difficulty understanding where to place the pagination code
I hope this code can help you. You only need to create an ViewController and then copy-paste the code.
// CarruselViewController.m
//
// Created by Rosendo Castillo Perez on 2/25/14.
// Copyright (c) 2014 Fundtech. All rights reserved.
//
#import "CarruselViewController.h"
#interface CarruselViewController ()
{
NSMutableArray *_CarouselView;
CGFloat _CurrentAngle,_LastAngle, _AngleToAdd;
UITouch * _TrackingTouch;
NSTimer * _AnimationTimer;
}
#end
#implementation CarruselViewController
#pragma mark -
#pragma mark - VIEW LIFE CYCLE
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:(BOOL)animated];
// VIEW FRAME
CGRect Frame = CGRectMake(-40, -40, 80, 40);
// CREATE 6 VIEWS
_CarouselView = [[NSMutableArray alloc] initWithCapacity:6];
int c = 0;
while(c < 5)
{
UILabel *View = [[UILabel alloc] initWithFrame:Frame];
View.backgroundColor = [UIColor colorWithRed:(c&4) ? 1.0 : 0.0 green:(c&2) ? 1.0 : 0.0 blue:(c&1) ? 1.0 : 0.0 alpha:1.0];
[View setTextAlignment:NSTextAlignmentCenter];
[View setTextColor:[UIColor whiteColor]];
[View setFont:[UIFont boldSystemFontOfSize:14]];
[View setText:[NSString stringWithFormat:#"%d",c]];
[_CarouselView addObject:View];
[self.view addSubview:View];
c++;
}
_CurrentAngle = _LastAngle = 0.0f;
[self setCarouselAngle:_CurrentAngle];
}
#pragma mark -
#pragma mark - VIEW TOUCH GESTURE
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(!_TrackingTouch)
{
_TrackingTouch = [touches anyObject];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
_LastAngle = _CurrentAngle;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
// USE MOVEMENT TO DEVICE HOW MUCH TO ROTATE THE CAROUSEL
CGPoint LocationNow = [_TrackingTouch locationInView:self.view];
CGPoint LocationThen = [_TrackingTouch previousLocationInView:self.view];
_LastAngle = _CurrentAngle;
_CurrentAngle += (LocationNow.x - LocationThen.x) * 180.0f / self.view.bounds.size.width;
// the 180.0f / self.view.bounds.size.width just says "let a full width of my view
// be a 180 degree rotation"
// and update the view positions
[self setCarouselAngle:_CurrentAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches containsObject:_TrackingTouch])
{
_TrackingTouch = nil;
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:#selector(animateAngle) userInfo:nil repeats:YES];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
#pragma mark -
#pragma mark - CAROUSEL ACTIONS
- (void)setCarouselAngle:(float)Angle
{
// ANGLE TO ADD AFTER EACH ELEM
_AngleToAdd = 360.0f / [_CarouselView count];
// APPLY TO ALL VIEWS
for(UIView *View in _CarouselView)
{
float AngleInRadians = Angle * M_PI / 180.0f;
// GET LOCATION
float x = (self.view.bounds.size.width * 0.5f) + 100.0f * sinf(AngleInRadians);
float y = ((self.view.bounds.size.height-200) * 0.5f) + 40.0f * cosf(AngleInRadians);
// ADJUST SCALE BETWEEN 0.75 0.25
float Scale = 0.75f + 0.25f * (cosf(AngleInRadians) + 1.0);
// APPLY TRANSFORMATION
View.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(x, y), Scale, Scale);
// TWEAK ALPHA
View.alpha = 0.1f + 0.5f * (cosf(AngleInRadians) + 1.0);
// SETTING Z POSITION
View.layer.zPosition = Scale;
// GET THE NEXT ANGLE
Angle += _AngleToAdd;
}
}
- (void)animateAngle
{
float AngleNow = _CurrentAngle;
_CurrentAngle += (_CurrentAngle - _LastAngle) * 0.97f;
_LastAngle = AngleNow;
// PUSH THE NEW ANGLE
[self setCarouselAngle:_CurrentAngle];
if(fabsf(_LastAngle - _CurrentAngle) < 0.1)
{
_CurrentAngle = ((int)_CurrentAngle % 360);
if (_CurrentAngle < 0.0)
{
_CurrentAngle += 360.0;
}
[self setCarouselAngle:_CurrentAngle];
int currentAngle = (int) _CurrentAngle;
int angleToAdd = (int) _AngleToAdd;
int residuo = currentAngle % angleToAdd;
if (residuo != 0)
{
forward = (residuo > (angleToAdd / 2));
[_AnimationTimer invalidate];
_AnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(centerAngle) userInfo:nil repeats:YES];
}
else
{
NSLog(#"angle: %d - index: %d",currentAngle,([_CarouselView count] - ((currentAngle / angleToAdd) % [_CarouselView count])));
}
}
}
BOOL forward = TRUE;
- (void)centerAngle
{
_CurrentAngle += (forward?1.0:-1.0);
[self setCarouselAngle:_CurrentAngle];
int currentAngle = (int) _CurrentAngle;
int angleToAdd = (int) _AngleToAdd;
int residuo = currentAngle % angleToAdd;
if (residuo == 0)
{
_LastAngle = _CurrentAngle = currentAngle;
[self setCarouselAngle:_CurrentAngle];
[_AnimationTimer invalidate];
_AnimationTimer = nil;
NSLog(#"angle: %d - index: %d",currentAngle,([_CarouselView count] - ((currentAngle / angleToAdd) % [_CarouselView count])));
}
}
#end

Zoom issue with UIImageView

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.

collision with moving objects

I have tried to write a collision with the moving "floats" but did not succeed. Is something maybe in the wrong place of the "collision" code?
//
// FruitsView.m
//
#import "FruitsView.h"
#import "Constants.h"
#import "Utilities.h"
#define kFloat1Speed 0.15
#define kFloat2Speed 0.3
#define kFloat3Speed 0.2
#interface FruitsView (Private)
- (void) stopTimer;
#end
#implementation FruitsView
#synthesize apple, float1, float2, float3, posFloat1, posFloat2, posFloat3;
-(void)onTimer {
float1.center = CGPointMake(float1.center.x+posFloat1.x,float1.cen ter.y+posFloat1.y);
if(float1.center.x > 380 || float1.center.x < -60)
posFloat1.x = -posFloat1.x;
if(float1.center.y > 100 || float1.center.y < -40)
posFloat1.y = -posFloat1.y;
float2.center = CGPointMake(float2.center.x+posFloat2.x,float2.cen ter.y+posFloat2.y);
if(float2.center.x > 380 || float2.center.x < -50)
posFloat2.x = -posFloat2.x;
if(float2.center.y > 150 || float2.center.y < -30)
posFloat2.y = -posFloat2.y;
float3.center = CGPointMake(float3.center.x+posFloat3.x,float3.cen ter.y+posFloat3.y);
if(float3.center.x > 380 || float3.center.x < -70)
posFloat3.x = -posFloat3.x;
if(float3.center.y > 100 || float3.center.y < -20)
posFloat3.y = -posFloat3.y;
if(CGRectIntersectsRect(apple.frame,float1.frame)) {
if(apple.center.y > float1.center.y) {
posApple.y = -posApple.y;
}
}
if(CGRectIntersectsRect(apple.frame,float2.frame)) {
if(apple.center.y > float2.center.y) {
posFloat2.y = -posFloat2.y;
}
}
if(CGRectIntersectsRect(apple.frame,float3.frame)) {
if(apple.center.y > float3.center.y) {
posFloat3.y = -posFloat3.y;
}
}
}
#pragma mark Initialisation/destruction
- (void)awakeFromNib {
[NSTimer scheduledTimerWithTimeInterval:0.0001 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
posFloat1 = CGPointMake(kFloat1Speed, 0);
posFloat2 = CGPointMake(kFloat2Speed, 0);
posFloat3 = CGPointMake(kFloat3Speed, 0);
timer = nil;
modeLock = lockNotYetChosen;
defaultSize = self.bounds.size.width;
modal = self.tag;
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationRepeatCount:1];
eadbea.transform = CGAffineTransformMakeScale(0.5,0.5);
[UIView commitAnimations];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationRepeatCount:1];
apple.transform = CGAffineTransformMakeScale(0.5,0.5);
[UIView commitAnimations];
}
#pragma mark Background animation processing
- (void) startTimer {
if (!timer) {
timer = [[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:#selector(timerTick:) userInfo:nil repeats:YES] retain];
}
}
- (void) stopTimer {
[timer invalidate];
[timer release];
timer = nil;
}
- (void) check:(CGPoint*)position delta:(CGSize*)delta halfSize:(CGSize)halfSize forBouncingAgainst:(CGSize)containerSize {
if ((position->x - halfSize.width)<0)
{
delta->width = fabsf(delta->width)*BOUNCE_DAMPING;
position->x = halfSize.width;
}
if ((position->x + halfSize.width)>containerSize.width)
{
delta->width = fabsf(delta->width)*-BOUNCE_DAMPING;
position->x = containerSize.width - halfSize.width;
}
if ((position->y - halfSize.height)<0)
{
delta->height = fabsf(delta->height)*BOUNCE_DAMPING;
position->y = halfSize.height;
}
if ((position->y + halfSize.height)>containerSize.height)
{
delta->height = fabsf(delta->height)*-BOUNCE_DAMPING;
position->y = containerSize.height - halfSize.height;
}
}
- (void) timerTick: (NSTimer*)timer {
dragDelta = CGSizeScale(dragDelta, INERTIAL_DAMPING);
if ((fabsf(dragDelta.width)>DELTA_ZERO_THRESHOLD) || (fabsf(dragDelta.height)>DELTA_ZERO_THRESHOLD))
{
CGPoint ctr = CGPointApplyDelta(self.center, dragDelta);
CGSize halfSize = CGSizeMake(self.bounds.size.width/4, self.bounds.size.height/4);
[self check:&ctr delta:&dragDelta halfSize:halfSize forBouncingAgainst:self.superview.bounds.size];
self.center = ctr;
}
else
{
[self stopTimer];
}
}
#pragma mark Input Handling
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet* allTouches = [event touchesForView:self];
if ([allTouches count]==1)
{
if (modeLock>lockNotYetChosen) return;
UITouch* anyTouch = [touches anyObject];
lastMove = anyTouch.timestamp;
CGPoint now = [anyTouch locationInView: self.superview];
CGPoint then = [anyTouch previousLocationInView: self.superview];
dragDelta = CGPointDelta(now, then);
self.center = CGPointApplyDelta(self.center, dragDelta);
[self stopTimer];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet* allTouches = [event touchesForView:self];
if ([touches count]==[allTouches count])
{
modeLock = lockNotYetChosen;
if ((event.timestamp - lastMove) > MOVEMENT_PAUSE_THRESHOLD)
return;
if ((fabsf(dragDelta.width)>INERTIA_THRESHOLD) || (fabsf(dragDelta.height)>INERTIA_THRESHOLD))
{
[self startTimer];
}
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
modeLock = lockNotYetChosen;
[self stopTimer];
}
- (void)dealloc
{
[float1 release];
[float2 release];
[float3 release];
[apple release];
[bear_head release];
[self stopTimer];
[super dealloc];
}
#end
Rather than doing all your floats, just use two NSRect and check if they intersect using NSIntersectionRect(rectA, rectB). Then you could do something like if(!NSIsEmptyRect(NSIntersectionRect(playerRect, monsterRect))) gameOver();
Cheers
Nik

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.