我目前有一个imageView,我可以使用panGestureRecognizer和以下方法在屏幕上拖动:
- (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];
}
目前可以将图像拖离屏幕以使其仅部分可见,我想知道是否有办法在屏幕边缘停止图像?我知道它应该是可能的,我只是在挣扎于逻辑。
答案 0 :(得分:5)
您是否尝试过使用CGRectContainsRect
?
您可以将其用作panDetected:
内部的支票,只有在返回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];
}
}
答案 1 :(得分:1)
您应该检查imageview的帧是否仍然在当前视图的帧中(或屏幕边界)。
if ( CGRectContains(self.view.frame, self.imageView.frame) )
// is inside
else
//is outside or intersecting