1

I currently have an imageView which I can drag around the screen using a panGestureRecognizer and the following method:

- (void)panDetected:(UIPanGestureRecognizer *)panRecognizer {
  CGPoint translation = [panRecognizer translationInView:self.view];
  CGPoint imageViewPosition = self.imageView.center;
  imageViewPosition.x += translation.x;
  imageViewPosition.y += translation.y;

  self.imageView.center = imageViewPosition;
  [panRecognizer setTranslation:CGPointZero inView:self.view];
}

Currently the image can be dragged off the screen so that it is only partially visible, I would like to know if there is a way to stop the image at the edge of the screen? I know it should be possible, I am just struggling with the logic.

4

2 回答 2

5

Have you tried using CGRectContainsRect?

You could use this as a check inside of your panDetected: and only allow translation if it returns YES.

- (void)panDetected:(UIPanGestureRecognizer *)panRecognizer {
    CGPoint translation = [panRecognizer translationInView:self.view];
    CGPoint imageViewPosition = self.imageView.center;
    imageViewPosition.x += translation.x;
    imageViewPosition.y += translation.y;

    CGFloat checkOriginX = self.imageView.frame.origin.x + translation.x; // imageView's origin's x position after translation, if translation is applied
    CGFloat checkOriginY = self.imageView.frame.origin.y + translation.y; // imageView's origin's y position after translation, if translation is applied

    CGRect rectToCheckBounds = CGRectMake(checkOriginX, checkOriginY, self.imageView.frame.size.width, self.imageView.frame.size.height); // frame of imageView if translation is applied

    if (CGRectContainsRect(self.view.frame, rectToCheckBounds)){
        self.imageView.center = imageViewPosition;
        [panRecognizer setTranslation:CGPointZero inView:self.view];
    }
}
于 2012-07-24T15:00:20.813 回答
1

You should check if the imageview's frame is still in the current view's frame (or the screen bounds).

   if ( CGRectContains(self.view.frame, self.imageView.frame) ) 
    // is inside
    else 
    //is outside or intersecting 
于 2012-07-24T14:45:27.747 回答