2017-05-31 29 views
0

我需要像素化/從封閉的2D多邊形獲得點。不勾勒,但用「像素」體素填充,以檢索它們的位置作爲點。 現在我有用於線柵格的C#代碼,有沒有類似於多邊形的方法?Bresenhams多邊形C#

回答

0

只需使用DrawLine()繪製一個多邊形。沒有繪製多邊形的具體算法。

void DrawPoly(IEnumerable<Point> points) 
{ 
    endpoints = points.Skip(1).Concat(new []{points.First()}); 
    pairs = points.Zip(endpoints, Tuple.Create); 

    for(var pair in pairs) 
    { 
     DrawLine(pair.Item1, pair.Item2); 
    } 
} 

void DrawLine(Point p1, Point p2) 
{ 
    // Your Bresenham code here 
} 

據編輯,你要填充的多邊形。如果您想手動執行此操作,請嘗試使用these之一。

聽起來好像你想要一個包含多邊形的所有座標的大列表。有可能有更好的方法來解決潛在的問題。但是,您有兩種選擇:

  • 在繪製每個點時存儲它。這要求您重寫上述算法。
  • 使用現有庫繪製多邊形。然後,把得到的圖像和附加座標圖像矩陣,它壓扁成一維列表,然後過濾掉非黑值:

    /* (0,0), (0,1), ..., (w,h) */ 
    grid = Enumerable.Range(0, width) 
        .SelectMany(x => Enumerable.Range(0, height) 
         .Select(y => new Point(x, y))); 
    
    flattened = image.SelectMany(p => p) 
        .Zip(grid, (a,b) => new {PixelValue = a, Coordinate = b}); 
    
    filledPoints = flattened.Where(p => p.PixelValue == 0) 
        .Select(p => p.Coordinate); 
    
+0

也許我的問題是不準確的,我正在尋找如何用像素填充多邊形並檢索它們的位置。像體素化一樣。 –

+1

聽起來像是在尋找[多邊形填充算法](https://www.tutorialspoint.com/computer_graphics/polygon_filling_algorithm.htm)。那裏列出了一些。如果要提取所有點的列表,可以:1.在繪製點時存儲點,或2.將座標附加到圖像矩陣,將其平鋪到一維列表中,然後執行一個'.Where (p => p.PixelValue == 0)'。 –

+0

如果我有繪製多邊形並填充它的簡單函數,如何附加圖像矩陣?見下面我的功能 –

0

如何我這件事情與矩陣連接存儲填充像素?

public static List<Tuple<int, int>> PixelizePolygon(PaintEventArgs e) 
{ 
    List<Tuple<int,int>> pixels = new List<Tuple<int, int>>(); 

    // Create solid brush. 
    SolidBrush blueBrush = new SolidBrush(Color.Blue); 

    // Create points that define polygon. 
    PointF point1 = new PointF(50.0F, 50.0F); 
    PointF point2 = new PointF(100.0F, 25.0F); 
    PointF point3 = new PointF(200.0F, 5.0F); 
    PointF point4 = new PointF(250.0F, 50.0F); 
    PointF point5 = new PointF(300.0F, 100.0F); 
    PointF point6 = new PointF(350.0F, 200.0F); 
    PointF point7 = new PointF(250.0F, 250.0F); 
    PointF[] curvePoints = { point1, point2, point3, point4, point5, point6, point7 }; 

    // Define fill mode. 
    FillMode newFillMode = FillMode.Winding; 

    // Fill polygon to screen. 
    e.Graphics.FillPolygon(blueBrush, curvePoints, newFillMode); 



    return pixels; 

}