【问题标题】:Find direction from rectangle points从矩形点查找方向
【发布时间】:2020-08-02 19:31:08
【问题描述】:

我试图从四个坐标中找出拐角的方向。也许一个例子比我的话更能描述..

    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 个坐标点的列表。尝试根据它们的方向将它们分开,例如左上角、右上角、左下角、右下角等。 但是我的代码不能正常工作(右上角和左下角都是错误的),请您帮我解决这个问题,以及如何提高效率?

【问题讨论】:

    标签: math canvas geometry coordinates draw


    【解决方案1】:

    您错过了 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]);
    }
    

    【讨论】:

    • 天才!非常感谢
    • 我使用这个自适应限制:// after "var points = [" block: minX = Math.min(...points.map(m =&gt; m[0])); minY = Math.min(...points.map(m =&gt; m[1])); maxX = Math.max(...points.map(m =&gt; m[0])); maxY = Math.max(...points.map(m =&gt; m[1])); var topLeft =[minX, maxY]; var topRight =[maxX, maxY]; var bottomRight =[maxX, minY]; var bottomLeft =[minX, minY]; // continue from "points.forEach((p) {" block
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2012-02-06
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多