点对点矩形测试 [英] Point-in-rectangle testing

查看:59
本文介绍了点对点矩形测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个矩阵

/// as if the create a rectangle
int [][] loc = {
  {5, 15},//(x1, y1)
  {5, 30}, // (x1, y2)
  {20, 15},// (x2, y1)
  {20, 30}, // (x2, y2)
}

// this are the point that i want to check if they are in the rectangular range or not
int [] [] point = {
  {6, 16}, //(x, y)
  {3, 17}, //(x, y)
} 

我想要的方法可以取点并搜索是否在loc范围内或不使用
x1< x< x2 y1< y< y2

I want i method that can take the point and search if it in the loc range or not by using x1<x<x2 and y1<y<y2

推荐答案

点(x,y)位于矩形(x1,y1) - (x2,y2)内,如果

A point (x, y) is inside a rectangle (x1,y1) - (x2, y2) if

(x1< = x< = x2)(y1< = y< = y2)

(x1 <= x <= x2) and (y1 <= y <= y2)

您的代码应如下所示(这实际上是C代码,但JavaScript不应该有太大差异):

Your code should look like this (this actually is C code, but JavaScript shouldn't be much different):

 x1 = loc[0][0];
 x2 = loc[2][0];
 y1 = loc[0][1];
 y2 = loc[2][1];
 for (int i = 0; i < num_points; i++) {
   if ((x1 <= point[i][0]) && (point[i][0] <= x2) && 
       (y1 <= point[i][1]) && (point[i][1] <= y2)) {
     // This point is inside the rectangle - insert code here
   } else {
     // This point is not inside the rectangle - insert code here
   }
 }

请注意,这只适用于(x1< = x2)和(y1< = y2),所以你可能会这样做也许通过使用它来确保上面的前四行:

Note that this will only work if (x1 <= x2) and (y1 <= y2), so you might perhaps make sure by using this instead the first four lines above:

x1 = Math.Min(loc[0][0], loc[2][0]);
x2 = Math.Max(loc[0][0], loc[2][0]);
y1 = Math.Min(loc[0][1], loc[2][1]);
y2 = Math.Max(loc[0][1], loc[2][1]);

这篇关于点对点矩形测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆