1

I am currently using UIPanGestureRecognizer to translate an image within my ipad screen but the problem is the image is going outside the screen. So how can i able to restrict the image movement outside ipad screen.

- (void)translate:(UIPanGestureRecognizer *)gesture {
    CGPoint myTranslation = [gesture translationInView:self];
    self.transform = CGAffineTransformTranslate(self.transform, myTranslation.x, myTranslation.y);
    [gesture setTranslation:CGPointZero inView:self];
}

2 Answers 2

1

You should check bounds and determine if the new position of the image is valid or not. Then you may apply the transform or not according to that.

2
  • 1
    Can you post the sample snippet how can i do this as i am new to ios
    – user930195
    Nov 3, 2011 at 7:09
  • I posted a relevant code snippet in another answer. It's hard to say more without seeing all the code. Hope it helps. Nov 3, 2011 at 8:47
0

This code is from one of my projects - SSPhotoCropperViewController. Here I let the user move an image in a scrollview, but I don't want them to move the image outside the scrollview's bounds. I handle UIControlEventTouchDragInside event of the imageview, determine the new position and I check whether the new position is valid then decide to move the image or not. Here is the code snippet for that. It's hard to say more without seeing all the code. You can use the idea here and apply it to your case, it shouldn't be too difficult. Hope this helps.

- (BOOL) isRectanglePositionValid:(CGPoint)pos
{
    CGRect innerRect = CGRectMake((pos.x + 15), (pos.y + 15), 150, 150);
    return CGRectContainsRect(self.scrollView.frame, innerRect);
}

- (IBAction) imageMoved:(id)sender withEvent:(UIEvent *)event
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];

    CGPoint prev = _lastTouchDownPoint;
    _lastTouchDownPoint = point;
    CGFloat diffX = point.x - prev.x;
    CGFloat diffY = point.y - prev.y;

    UIControl *button = sender;
    CGRect newFrame = button.frame;
    newFrame.origin.x += diffX;
    newFrame.origin.y += diffY;
    if ([self isRectanglePositionValid:newFrame.origin]) {
        button.frame = newFrame;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.