Adding pinch/zoom controls

Pinch/zoom is a two-finger gesture in which if you place two fingers on the screen and bring the fingers closer, the image will be scaled down in size, and if you move the fingers apart, the image is enlarged.

Getting ready

For this, we need an image to work with; so, import the Bg image from the first chapter to work with. Make the sprite a global variable as we will need to access it in another function.

So, in the MainScene.h file, we will add an instance of CCSprite as CCSprite* backgroundImage;.

Also, we will add a global float called currentScale to track the current scale value of the background image.

Next, in the init function, we will initialize the variable, as follows:

backgroundImage = [CCSpritespriteWithImageNamed:@"Bg.png"];
backgroundImage.position = CGPointMake(winSize.width/2, winSize.height/2);
[selfaddChild:backgroundImage];

How to do it…

We will add the pinch/zoom recognizer in the init function and set the desired function name that will be responsible for pinching and zooming the image, as follows:

// ** PinchZoom ** //
UIPinchGestureRecognizer* pinchRecognizer = [[UIPinchGestureRecognizeralloc] initWithTarget:self action:@selector(handlePinchGesture:)];

[[UIApplicationsharedApplication].delegate.windowaddGestureRecognizer:pinchRecognizer];

Next, we will add the following function:

-(void)handlePinchGesture:(UIPinchGestureRecognizer*)recognizer{

  NSLog(@"pinch zoom");
  backgroundImage.scale = recognizer.scale;

}

Here, we got the scale value from the recognizer and assigned it to the image.

How it works…

If you are running it on a device, place two fingers on the screen and bring them close and take them away from each other. If you are using a simulator, you can press the Alt key and drag the mouse on the screen to see the effect.

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.38