我试图从四个坐标中找出角的方向。也许一个例子比我的话更能描述..
var points = [
[0, 0], // top-left
[50, 0], // top-right
[50, 50], // bottom-right
[0, 50], // bottom-left
]; // order can be random
var topLeft =[9999, 9999];
var topRight =[0, 9999];
var bottomRight =[0, 0];
var bottomLeft =[9999, 0];
points.forEach((p) {
if (p[0] < topLeft[0] && p[1] < topLeft[1]) topLeft = p;
if (p[0] > topRight[0] && p[1] < topRight[1]) topRight = p;
if (p[0] > bottomRight[0] && p[1] > bottomRight[1]) bottomRight = p;
if (p[0] < bottomLeft[0] && p[1] > bottomLeft[1]) bottomLeft = p;
});
print([tl, tr, br, bl]);
// [[0, 0], [50, 0], [50, 50], [50, 50]] - wrong
// [[0, 0], [50, 0], [50, 50], [0, 50]] - right
我有一个包含 4 个坐标点的列表。尝试根据方向将它们分开,例如左上、右上、左下、右下等。 但我的代码无法正常工作(右上角和左下角错误),您能帮我解决这个问题吗?以及如何提高效率?
最佳答案
您错过了 if 条件中的=(等号)。 这是更新后的代码。
void main() {
var points = [
[0, 0], // top-left
[50, 0], // top-right
[50, 50], // bottom-right
[0, 50], // bottom-left
]; // order can be random
var topLeft =[9999, 9999];
var topRight =[0, 9999];
var bottomRight =[0, 0];
var bottomLeft =[9999, 0];
points.forEach((p) {
if (p[0] <= topLeft[0] && p[1] <= topLeft[1]) topLeft = p;
if (p[0] >= topRight[0] && p[1] <= topRight[1]) topRight = p;
if (p[0] >= bottomRight[0] && p[1] >= bottomRight[1]) bottomRight = p;
if (p[0] <= bottomLeft[0] && p[1] >= bottomLeft[1]) bottomLeft = p;
});
print([topLeft, topRight, bottomRight, bottomLeft]);
}
关于math - 从矩形点查找方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220234/