簡體   English   中英

在目標C中定義位置的矩形

[英]Define a rectangle of locations in objective-C

我在Iphone應用程序中有一個圖像,我希望當用戶在定義的區域(位置范圍或由矩形定義的區域)中輕按一個位置時,它會觸發另一個事件。 我知道如何獲得一個位置,但是我不知道如何定義矩形區域。 我正在尋找一種簡單的方法來實現它。 謝謝

如果要使矩形可見,可以將圖像視圖添加到視圖中並設置點擊識別器。 但是,如果您不想使矩形可見,則可以覆蓋touchesBegan:withEvent:方法並使用CGRectContainsPoint:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    CGRect rect = CGRectMake(0.0, 0.0, 100, 100); //<- this is the rectangle you do check on
    if (CGRectContainsPoint(rect, touchLocation)) {
        NSLog(@"You tapped inside rectangle");
    }
    else {
        NSLog(@"You missed rectangle");
    }
}

將您的區域定義為CGRect並獲取觸摸的CGPoint 然后使用CGRectContainsPoint檢查CGRectContainsPoint

如果需要從點列表創建CGRect ,則需要迭代這些點並找到最大和最小x和y值,則可以使用以下方法創建CGRect

CGRectMake(minX, minY, maxX - minX, maxY - minY);

也許您可以創建一個UIView並添加一個手勢識別器,如下所示:

UIView *customView = [UIView new];
customView.frame = CGRectMake(....); // as Wain suggest
[self.view addSubview:customView];

UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget: self
  action: @selector(someMethod)];
[customView addGestureRecognizer:tapGesture];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM