2013-04-25 26 views
1

我想獲得隨機繪製的矩形排列在窗體上彼此相鄰,但我的循環不工作,給我不想要的結果,任何幫助將不勝感激。如何將隨機繪製的矩形垂直堆疊在一起?

我已經創建了一個創建隨機矩形然後將它們存儲在列表集合中的方法。

List<Rectangle> rectangleCollection = new List<Rectangle>(); 

    void CreateRectangle() 
    { 
     int TallestRectangle = 0; ; 
     int PrevRecX = 0; 
     int PrevRecY = 0; 

     Pen pen = new Pen(Color.Black); 
     Graphics graphic = this.CreateGraphics(); 


     foreach (Rectangle rect in rectangleCollection) 
     { 
      if (rect.Height > TallestRectangle) 
       TallestRectangle = rect.Height; 
     } 

     foreach (Rectangle rect in rectangleCollection) 
     { 
      if (PrevRecX + PrevRecY == 0) 
      { 
       graphic.DrawRectangle(pen, new Rectangle(rect.X, (TallestRectangle - rect.Height), rect.Width, rect.Height)); 
      } 
      else 
      { 
       graphic.DrawRectangle(pen, new Rectangle((PrevRecX + PrevRecY), (TallestRectangle - rect.Height), rect.Width, rect.Height)); 
      } 
      PrevRecX = rect.X; 
      PrevRecY = rect.Width; 
     } 

    } 

    void GetRandomRectangle() 
    { 
     Random ran = new Random(); 

     int x = 0; 
     int y = 0; 

     int width = ran.Next(100, 500); 
     int height = ran.Next(200, 700); 

     Rectangle rec = new Rectangle(x, y, width, height); 

     rectangleCollection.Add(rec); 
    } 
+1

什麼「令人失望的結果」?你得到了什麼?這與你的期望有什麼不同? – Corak 2013-04-25 07:18:55

+0

如果問題是所有的矩形都是相同的大小:每次調用'GetRandomRectangle'時不要創建一個'Random'對象。有*一個*靜態的,並使用它。 – Corak 2013-04-25 07:24:07

+0

@Corak我的不想要的結果是我的矩形沒有對齊,並且重疊,也請給我一個有一個靜態隨機對象並使用它的例子(對不起,我是一個新的)。 – TheJunior 2013-04-25 07:29:49

回答

0

你的第二個foreach看起來太複雜了。我不認爲你真的需要PrevRecX。試試看看它是否符合你的期望。

void CreateRectangle() 
{ 
    int TallestRectangle = 0; 
    int PrevRecY = 0; 

    Pen pen = new Pen(Color.Black); 
    Graphics graphic = this.CreateGraphics(); 

    foreach (Rectangle rect in rectangleCollection) 
    { 
    if (rect.Height > TallestRectangle) 
     TallestRectangle = rect.Height; 
    } 

    foreach (Rectangle rect in rectangleCollection) 
    { 
    graphic.DrawRectangle(pen, new Rectangle(rect.X + PrevRecY, (TallestRectangle - rect.Height), rect.Width, rect.Height)); 
    PrevRecY += rect.Width; // note the += 
    } 
} 

對於static Random,只是申報方式外的變量,並使用它裏面,這樣的:

private static Random ran = new Random(); 
void GetRandomRectangle() 
{ 
    int x = 0; 
    int y = 0; 

    int width = ran.Next(100, 500); 
    int height = ran.Next(200, 700); 

    // ... 
} 
+0

非常感謝你的作品!現在,它們是垂直堆疊的,我需要計算輸出矩形,然後水平顯示它們,同時保持它們垂直堆疊時的形狀。 – TheJunior 2013-04-25 08:02:49

+0

如果你有垂直堆疊覆蓋,你應該很容易地自己水平堆疊。主要計算最寬的矩形,相應地計算位置和'+ ='高度。什麼是「輸出矩形」?那是圍繞着所有顯示的矩形嗎?這應該有與tallesRectangle相同的高度,寬度應該是所有寬度的總和。 – Corak 2013-04-25 08:50:02

+0

這基本上是我必須實現的:http://social.msdn.microsoft.com/Forums/getfile/139053 – TheJunior 2013-04-25 09:01:22