首页 > 解决方案 > 作为象限一部分的 JPanel 的 x,y 坐标

问题描述

我的程序有问题。我想要实现的是一种理解象限所在的点(x,y)的方法。

我试图实现的象限概念如下: 在此处输入图像描述

我有一个矩形,从中我有所有角度和边缘的坐标。给定空间中的另一个点,在 2D 空间中,我想知道顶部、底部、左侧和右侧之间的位置。

先感谢您。

编辑:

到目前为止,我已经写了这段代码:

Point A=t.src;  //center point of the first square
Point B=t.dest;  //center point of the second square

int destHeight=t.destDim.height;
int destWidth=t.destDim.width;

int m = destHeight/destWidth;
int b = B.y -(m*B.x);
int d = B.y +(m*B.x);

if(A.y >= m*A.x +b){
    if(A.y >= -m*A.x+d){
        System.err.println("2 - Source on BOTTOM");
    }else{ //A.y < -m*A.x+d
        System.err.println("2 - Source on LEFT");
    } 
}else if(A.y < m*A.x + b){
    if(A.y>= -m*A.x +d){
        System.err.println("2 - Source on RIGHT");
    }else{ //A.y < m*A.x + d
        System.err.println("2 - Source on TOP");
    }
}

问题是我仍然没有预期的结果。这就是我得到 的:问题的视频演示

正如您从输出控制台中看到的那样,它永远不会提示源在左侧,它只是从上到下转换。

标签: javaswinggeometryjava-2d

解决方案


让矩形以零为中心并且具有边长a(水平)和b。(如果它不是以零为中心的,只需从点中减去中心坐标)。那么线条有简单的方程

m = b / a 
y = m * x   //L1
y = -m * x  //L2

上象限的点位于两条线之上,右象限的点位于 L2 之上但 L1 之下,依此类推。

对于点坐标(px, py)

 mpx = m * px
 if (py >= mpx) :
     if (py >= -mpx) :
          top
     else:
          left
 else:    
     if (py >= -mpx) :
          right
     else:
          bottom

推荐阅读