Search code examples
iosgpuimageuipinchgesturerecognizer

Calculate pinch value for bulge distortion filter radius


I need to increase and decrease GPUImagePinchDistortionFilter radius according to pinch, I am using pinch gesture recognizer and storing the starting scale of the gesture recognizer. I need to calculate the pinch scale between -2.0 and 2.0. Here is my code.

if([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
    lastScale = [gestureRecognizer scale];
}

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
    [gestureRecognizer state] == UIGestureRecognizerStateChanged) {

    CGFloat currentScale = [[[gestureRecognizer view].layer valueForKeyPath:@"transform.scale"] floatValue];

    CGFloat kMaxScale = 2.0;
    CGFloat kMinScale = -2.0;

    CGFloat newScale = 1.0 - (lastScale - [gestureRecognizer scale]);

    newScale = MIN(newScale, kMaxScale / currentScale);
    newScale = MAX(newScale, kMinScale / currentScale);

    [pinchDistortionFilter setRadius:newScale];
}

I have followed some posts to do this. but still stuck, also I need to set this every time the user pinches but the radius must be within the min and max. actually I am confused how to achieve this, can anyone help me with this ?

Thank You.


Solution

  • I think you should try to save the lastScale and radius too in correct place, and the radius should be > 0 see my answer below for my implementation, it might help you.

    float currentApplicableScale = (gestureRecognizer.scale/2);
    
       if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
           lastRadius = lastScale;
       }else if (gestureRecognizer.state==UIGestureRecognizerStateBegan) {
           firstScale = currentApplicableScale;
       }else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
           float radius = currentApplicableScale;
    
           if (lastRadius<=0) {
               lastRadius = 0.25;
           }
    
           radius = radius - (firstScale - lastRadius);
    
           if (radius>0 && radius < 0.5) {
    
                [(GPUImagePinchDistortionFilter*)pinchFilter setRadius:radius];
    
    
               lastScale = radius; //Save here
           }
       }