gpt4 book ai didi

Android:找到Point和Rect之间最短距离的最佳方法?

转载 作者:搜寻专家 更新时间:2023-11-01 08:16:06 25 4
gpt4 key购买 nike

似乎应该有一些方便的方法来做到这一点?

我找不到,所以我拼凑了下面的算法。它是内存/计算最优的吗?

感谢:

编辑:原来的算法是错误的,也许这个更好?

public static float minDistance(RectF rect, PointF point)
{
if(rect.contains(point.x, point.y))
{
//North line
float distance = point.y - rect.top;

//East line
distance = Math.min(distance, point.x - rect.left);

//South line
distance = Math.min(distance, rect.bottom - point.y);

//West line
distance = Math.min(distance, rect.right - point.x);

return distance;
}
else
{
float minX, minY;

if (point.x < rect.left)
{
minX = rect.left;
}
else if (point.x > rect.right)
{
minX = rect.right;
}
else
{
minX = point.x;
}

if (point.y < rect.top)
{
minY = rect.top;
}
else if (point.y > rect.bottom)
{
minY = rect.bottom;
}
else
{
minY = point.y;
}

float vectorX = point.x - minX;
float vectorY = point.y - minY;

float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));

return distance;
}
}

最佳答案

只需取最近点,然后计算到该点的距离。在我的脑海中:

    float closestX, closestY;

if(point.x >= x1 && point.x <= x2 && point.y >= y1 && point.y <= y2)
{
float bestDistance = point.y - y1;
bestDistance = Math.min(distance, y2 - point.y);
bestDistance = Math.min(distance, point.x - x1);
bestDistance = Math.min(distance, x2 - point.x);

return bestDistance;
}

if (point.x < x1) {
closestX = x1;
} else if (point.x > x2) {
closestX = x2;
} else {
closestX = point.x;
}

if (point.y < x1) {
closestY = y1;
} else if (point.y > y2) {
closestY = y2;
} else {
closestY = point.y;
}

float vectorY = point.x - closestX;
float vectorY = point.Y - closestY;

float distance = sqrtf((vectorX * vectorX) + (vectorY * vectorY));

关于Android:找到Point和Rect之间最短距离的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com