触摸移动屏幕边界,如何限制矩形移出屏幕边界



我正在尝试通过屏幕边界限制矩形的移动。逻辑很简单,你点击矩形内部(不在哪里)并拖动它。它跟随您的手指,当矩形的边框到达屏幕边界时必须停止。

- (void)viewDidLoad {
[super viewDidLoad];
rect.backgroundColor = [UIColor redColor];

}

然后我试着弄清楚水龙头在哪里,如果它在矩形内,我会改变矩形的颜色

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//NSLog(@"%s", __PRETTY_FUNCTION__);
UITouch *touch = touches.anyObject;
if (touch.view == rect) {
    rect.backgroundColor = [UIColor greenColor];
    isSelectedRect = YES;
    CGPoint point = [touch locationInView:self.view];
    CGPoint center = rect.center;
    delta = CGPointMake(point.x - center.x,
                        point.y - center.y);
} else {
    rect.backgroundColor = [UIColor redColor];
    isSelectedRect = NO;
}

}

之后我移动这个矩形

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
    if (isSelectedRect) {
        UITouch *touch = touches.anyObject;
        CGPoint point = [touch locationInView:self.view];
        rect.center = CGPointMake(point.x - delta.x,
                                  point.y - delta.y);
    }
}

最终,我需要编写一行代码,它将通过碎石的边界限制矩形的移动。我和用三元运算符制作它会是完美的。我将不胜感激任何帮助。

touchesMoved方法替换为下面的代码。希望它能帮助你;)

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  //NSLog(@"%s", __PRETTY_FUNCTION__);
  if (isSelectedRect) {
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.view];
    CGPoint newCenter = CGPointMake(point.x - delta.x,
                          point.y - delta.y);
    CGFloat rectHeight =  rect.frame.size.height;
    CGFloat rectWidth =  rect.frame.size.width;
    CGFloat screenWidth = self.view.frame.size.width;
    CGFloat screenHeight = self.view.frame.size.height;

    if (newCenter.x + rectWidth / 2 > screenWidth) {
      newCenter.x = screenWidth - rectWidth / 2;
    }
    if (newCenter.x - rectWidth / 2 < 0) {
      newCenter.x = rectWidth / 2;
    }
    if (newCenter.y + rectHeight / 2 > screenHeight) {
      newCenter.y = screenHeight - rectHeight / 2;
    }
    if (newCenter.y - rectHeight / 2 >= 0) {
      newCenter.y = rectHeight / 2;
    }
    rect.center = newCenter;
  }
}
if (CGRectContainsPoint(boundsRect, point)) {
    rect.center = CGPointMake(point.x - delta.x,
                                  point.y - delta.y);
} 

在这里,boundsRect 将是设备的矩形。

您必须注意,您在 touchesMoving 函数中移动的点是视点的中心点。为了限制它们超出视图边界,您必须检查可拖动视图的边界是否超出了平移点。

获取实际边界

CGPoint center = rect.center;
CGSize size = rect.size
CGRect originalRect = CGRectMake(center.x - size.width/2, center.y - size.height/2, size.width, size.height);

现在检查给定的矩形是否在所需的矩形内。

if (CGRectContainsRect(boundsRect, originalRect)) {
    // Here change the center of the view 
} 

我希望这有所帮助。

最新更新