Search code examples
iosswiftuigesturerecognizeruipinchgesturerecognizer

Scaling a UIView along one direction with UIPinchGestureRecognizer


In my app I have a draggable UIView to which I have added a UIPinchGestureRecognizer. Following this tutorial, as default the view is scaled along both x and y directions. Is it possibile to scale along only one direction using one finger? I mean, for example, I tap the UIView both with thumb and index fingers as usual but while I'am holding the thumb I could move only the index finger in one direction and then the UIView should scale along that dimension depending on the direction in which the index moves.

Actually, I have achieved this by adding pins to my UIView like the following:

enter image description here

I was just thinking my app might be of better use using UIPinchGestureRecognizer.

I hope I have explained myself, if you have some hints or tutorial or documentation to link to me I would be very grateful.


Solution

  • In CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale) update only one axis: X or Y with recognizer.scale and keep the other one 1.0f

    CGAffineTransformMakeScale(CGFloat sx, CGFloat sy)
    

    In order to know which axis you should scale, you need to do some math to see the angle between two fingers of a gesture and based on the angle to decide which axis to scale.

    Maybe something like

    enum Axis {
        case X
        case Y
    }
    
    func axisFromPoints(p1: CGPoint, _ p2: CGPoint) -> Axis {
        let absolutePoint = CGPointMake(p2.x - p1.x, p2.y - p1.y)
        let radians = atan2(Double(absolutePoint.x), Double(absolutePoint.y))
    
        let absRad = fabs(radians)
    
        if absRad > M_PI_4 && absRad < 3*M_PI_4 {
            return .X
        } else {
            return .Y
        }
    }