Reputation: 82
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.
Upvotes: 1
Views: 1319
Reputation: 2805
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];
}
}
Upvotes: 5
Reputation: 1694
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
Upvotes: 1