Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zooming in and out of a UIView

Tags:

xcode

ios

zooming

what is the best way to zoom in and out of a UIView with a simple method buttons. (e.i

(IBAction)zoomin:(int)distance
{
method here
}
(IBAction)zoomout:(int)distance
{
and here
}
like image 261
luca590 Avatar asked Feb 17 '11 22:02

luca590


2 Answers

It can be done using two finger gesture recognizer: You have to just write down:-

-(void)viewDidLoad
{
UIPinchGestureRecognizer *twoFingerPinch = [[[UIPinchGestureRecognizer alloc] 
                                           initWithTarget:self 
                                           action:@selector(twoFingerPinch:)] 
                                           autorelease];

[[self view] addGestureRecognizer:twoFingerPinch];
}

By this you have initialized an instance which will take care of two finger sensations on the Screen (or View on which you are applying this method) Now define what to do if you have recognized the two fingers:

- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer 
{
    NSLog(@"Pinch scale: %f", recognizer.scale);
    CGAffineTransform transform = CGAffineTransformMakeScale(recognizer.scale, recognizer.scale);
                                      // you can implement any int/float value in context of what scale you want to zoom in or out
    self.view.transform = transform;
}

The above defined method is called automatically not through the UIButton actions but it will solve your problem with simplicity If you strictly want to use zoom at IBAction then simply do this:

 -(IBAction)methodCalledOnClickingUIButton:(id)sender
{
    if(sender==zoomInButton)
     {
       scaleValue++;
     }
    else if(sender==zoomOutButton)
     {
       scaleValue--;
     }
     CGAffineTransform transform = CGAffineTransformMakeScale(scaleValue,scaleValue);
     self.view.transform = transform;
}

Where scaleValue is any float value..you can set this up according to your application requirement! I hope it will work fine for you! :)

like image 69
Kritanshu_iDev Avatar answered Oct 20 '22 02:10

Kritanshu_iDev


Swift 3, 4+

Detect zoom in/out with two fingers for a UIView. Here is an example listening on the main view:

override func viewDidLoad() {    
     var pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchedView))
     view.isUserInteractionEnabled = true
     view.addGestureRecognizer(pinchGesture)    
}

// Listener

@objc func pinchedView(sender: UIPinchGestureRecognizer) {
    if sender.scale > 1 {
        print("Zoom out")
    } else{
        print("Zoom in")
    }
}
like image 1
Tuan Huynh Avatar answered Oct 20 '22 04:10

Tuan Huynh