2016-04-08 65 views
0

我有这样Rectangle Rect = new Rectangle(0, 0, 300, 200); 一个矩形,我想在20个矩形5X4(5列,4行)这样分而绘制多个矩形

|'''|'''|'''|'''|'''| 
|...|...|...|...|...| 
|'''|'''|'''|'''|'''| 
|...|...|...|...|...| 
|'''|'''|'''|'''|'''| 
|...|...|...|...|...| 
|'''|'''|'''|'''|'''| 
|...|...|...|...|...| 

道道有人帮equaly划分呢?香港专业教育学院一直在努力解决这个问题像一小时:(

+0

不,的WinForms – Adrao

+0

你到底想达到什么目的? –

+0

我只想绘制20个更小的矩形,在另一个矩形内,就是这样。林创建一个自定义控件,我不能使用DataGridView – Adrao

回答

1

这应有助于:

鉴于你矩形:

Rectangle Rect = new Rectangle(0, 0, 300, 200); 

这将让subrectangles的列表:

List<RectangleF> GetSubRectangles(Rectangle rect, int cols, int rows) 
    { 
     List<RectangleF> srex = new List<RectangleF>(); 
     float w = 1f * rect.Width/cols; 
     float h = 1f * rect.Height/rows; 

     for (int c = 0; c < cols; c++) 
      for (int r = 0; r < rows; r++) 
       srex.Add(new RectangleF(w*c, h*r, w,h)); 
     return srex; 
    } 

请注意,返回RectangleF而不是Rectangle以避免精度损失。当你需要一个Rectangle你总是可以得到一个这样的:

Rectangle rec = Rectangle.Round(srex[someIndex]); 
在面板内部
+0

谢谢..只是我在找什么 – Adrao

1

要创建的20个矩形列表(像你想的话),你可以这样做:

List<Rectangle> list = new List<Rectangle>(); 
int maxWidth = 300; 
int maxHeight = 200; 
int x = 0; 
int y = 0; 
while (list.Count < 20) 
{ 
    for (x = 0; x < maxWidth; x += (maxWidth/5)) 
    { 
     for (y = 0; y < maxHeight; y += (maxHeight/4)) 
     { 
      list.Add(new Rectangle(x, y, (maxWidth/5), (maxHeight/4)); 
     } 
     y = 0; 
    } 
    x = 0; 
} 
+0

谢谢,你的解决方案也可以工作,但我试图使用尽可能少的循环。 – Adrao