Search code examples
iosimageimageviewcrop

Image Cropping in rectangle shape and it shud move


I want to crop an UIImageView in rectangular size and it Should be resizable, Please anyone help me, I am struggling.


Solution

  • You can use below code to add pan gesture from which you can move the imageview and pinch gesture through which you can resize the image

    -(void)addGesture {
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
        [panRecognizer setMinimumNumberOfTouches:1];
        [panRecognizer setMaximumNumberOfTouches:1];
        [imgView addGestureRecognizer:panRecognizer];
    
         UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(resize:)];
            [imgView addGestureRecognizer:pinchRecognizer];
    
    }
    
    -(void)move:(id)sender {
        [self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
        CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
    
        if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
            firstX = [[sender view] center].x;
            firstY = [[sender view] center].y;
        }
    
        translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY);
    
        [[sender view] setCenter:translatedPoint];
    }
    
    - (void)resize:(UIPinchGestureRecognizer *)recognizer
    {
    
        if([recognizer state] == UIGestureRecognizerStateBegan) {
            _lastScale = 1.0;
            if ([recognizer numberOfTouches] >= 2) { //should always be true when using a PinchGR
                CGPoint touch1 = [recognizer locationOfTouch:0 inView:self.imageForEditing];
                CGPoint touch2 = [recognizer locationOfTouch:1 inView:self.imageForEditing];
                CGPoint mid;
                mid.x = ((touch2.x - touch1.x) / 2) + touch1.x;
                mid.y = ((touch2.y - touch1.y) / 2) + touch1.y;
                CGSize imageViewSize = self.imageForEditing.frame.size;
                CGPoint anchor;
                anchor.x = mid.x / imageViewSize.width;
                anchor.y = mid.y / imageViewSize.height;
                self.imageForEditing.layer.anchorPoint = anchor;
            }
        }
    
        CGFloat scale = 1.0 - (_lastScale - [recognizer scale]);
    
        CGAffineTransform currentTransform = self.imageForEditing.transform;
        CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    
        [self.imageForEditing setTransform:newTransform];
    
        _lastScale = [recognizer scale];
    
    
    }