2013-04-16 40 views
5

可以說,我有我的第一點的結構:如何獲取兩個Point對象之間的所有點?

Point start = new Point(1, 9); 

和我的第二個:

Point end = new Point(4, 9); 

我想所有的起點和終點之間的點。因此,例如,我會想在數組中的2,9和3,9。 .NET有內置的東西嗎?

+9

http://en.wikipedia.org/wiki/Bresenham's_line_algorithm – Patashu

+2

有*擺在任意兩點之間的無限多的*點。你想要他們嗎? –

+0

@CodyGray一個'Point'包含兩個整數值。至少它在XNA的實現中是如此。 Patashu的鏈接可能是相關的。 –

回答

5

由於點之間沒有點,因此沒有構建函數。數學在兩點之間有一條線。在計算機圖形學方面,線條可能是反鋸齒的,所以不能四捨五入成爲整數。

如果您正在尋找創建所有整數的快速方法,我猜Bresenhams-Line-Algorithm將成爲您的選擇。但是,這是不是建設成.NET,你必須自己編寫它(或採取馬修·沃森的實現):

http://en.wikipedia.org/wiki/Bresenham's_line_algorithm

甚至還有專爲做fasther算法,但我會去布氏。

3

這就是我最終做的。正如@Cody Gray在他的評論中提到的那樣,有一條線上有無限的點。所以你需要指定你想要檢索的點數。

var line = new Line(new Point(10, 15), new Point(297, 316)); 
var points = line.getPoints(20); 

,將返回的20點的兩個端點(含)之間均勻分佈的一個點陣列:

我行類:

public class Line { 
    public Point p1, p2; 

    public Line(Point p1, Point p2) { 
     this.p1 = p1; 
     this.p2 = p2; 
    } 

    public Point[] getPoints(int quantity) { 
     var points = new Point[quantity]; 
     int ydiff = p2.Y - p1.Y, xdiff = p2.X - p1.X; 
     double slope = (double)(p2.Y - p1.Y)/(p2.X - p1.X); 
     double x, y; 

     --quantity; 

     for (double i = 0; i < quantity; i++) { 
      y = slope == 0 ? 0 : ydiff * (i/quantity); 
      x = slope == 0 ? xdiff * (i/quantity) : y/slope; 
      points[(int)i] = new Point((int)Math.Round(x) + p1.X, (int)Math.Round(y) + p1.Y); 
     } 

     points[quantity] = p2; 
     return points; 
    } 
} 


用法。希望有所幫助!

+0

你是一個壞蛋。 :O –

+0

它也可以用於對角線嗎? –

+0

@BirajZalavadia絕對! –

1

我知道自從你第一次問這個問題已經很長時間了,但我最近在尋找類似的東西,發現這個維基(https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm),其中包含僞代碼。

所以我已經實現了一個帶有僞代碼的函數來執行這個計算並將這些點添加到列表中。

public List<Point> GetPoints(Point p1, Point p2) 
{ 
    List<Point> points = new List<Point>(); 

    // no slope (vertical line) 
    if (p1.X == p2.X) 
    { 
     for (double y = p1.Y; y <= p2.Y; y++) 
     { 
      Point p = new Point(p1.X, y); 
      points.Add(p); 
     } 
    } 
    else 
    { 
     // swap p1 and p2 if p2.X < p1.X 
     if (p2.X < p1.X) 
     { 
      Point temp = p1; 
      p1 = p2; 
      p2 = temp; 
     } 

     double deltaX = p2.X - p1.X; 
     double deltaY = p2.Y - p1.Y; 
     double error = -1.0f; 
     double deltaErr = Math.Abs(deltaY/deltaX); 

     double y = p1.Y; 
     for (double x = p1.X; x <= p2.X; x++) 
     { 
      Point p = new Point(x, y); 
      points.Add(p); 
      Debug.WriteLine("Added Point: " + p.X.ToString() + "," + p.Y.ToString()); 

      error += deltaErr; 
      Debug.WriteLine("Error is now: " + error.ToString()); 

      while (error >= 0.0f) 
      { 
       Debug.WriteLine(" Moving Y to " + y.ToString()); 
       y++; 
       points.Add(new Point(x, y)); 
       error -= 1.0f; 
      } 
     } 

     if (points.Last() != p2) 
     { 
      int index = points.IndexOf(p2); 
      points.RemoveRange(index + 1, points.Count - index - 1); 
     } 
    } 

    return points; 
} 
相關問題