java判断点在矩形_java - 检测矩形中已知点的位置 - 堆栈内存溢出

我找到了一个很好的解决方案,适合我的问题。

首先,我尝试检测Rectangle的左上角和右下角。 为此,我从坐标系的源计算二维Vector的长度。 4个向量中最短的是左上角,最大的是右下角。 我尝试通过对两个已知点的简单坐标检查来检测其他两个点。 为避免出现小错误,右上角与左下角通过相同的检查,我通过x坐标对点进行排序。

这是代码:

private PointF[] checkPointLocation(PointF[] points){

double minLength = 100000000;

double maxLength = 0;

int minPos = 0;

int maxPos = 0;

for(int i = 0; i < points.length; i++){

double vLength = Math.abs(Math.sqrt((points[i].x * points[i].x) + (points[i].y * points[i].y)));

if(vLength < minLength) {

minLength = vLength;

minPos = i;

}

if(vLength > maxLength) {

maxLength = vLength;

maxPos = i;

}

}

PointF topLeft = points[minPos];

PointF bottomRight = points[maxPos];

Log.d(TAG, "TopLeft: " + topLeft);

Log.d(TAG, "BottomRight: " + bottomRight);

PointF topRight = null;

PointF bottomLeft = null;

Arrays.sort(points, (o1, o2) -> Float.compare(o1.x, o2.x));

for(int i = 0; i < points.length; i++){

PointF p = points[i];

Log.d(TAG, "Point: " + p);

if( p.equals(topLeft) || p.equals(bottomRight))

continue;

if(bottomLeft == null && p.x < bottomRight.x && p.y > topLeft.y)

bottomLeft = p;

if(topRight == null && p.x > topLeft.x && p.y < bottomRight.y)

topRight = p;

}

if(topRight == null){

throw new NullPointerException("topRight is null");

}

if(bottomLeft == null){

throw new NullPointerException("BottomLeft is null");

}

Log.d(TAG, "BottomLeft = " + bottomLeft);

Log.d(TAG, "TopRight = " + topRight);

PointF[] ccwPoints = {topLeft, bottomLeft, bottomRight, topRight};

return ccwPoints;

}

就我而言,此解决方案适用于所有可能的用户输入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值