2016-05-20 109 views
0

我試圖用一致的間距對齊一定數量的標籤。 for循環之後的對齊很好,但爲什麼第一個間距與其他間距不一致呢?標籤之間的一致間距c#

private void FrmMainGame_Load(object sender, EventArgs e) 
    { 
     Label l = new Label(); 
     int margin = 1; 
     int width = (this.ClientSize.Width + margin - l.Size.Width) /10 ; 
     l.BackColor = Color.Red; 
     l.BorderStyle = BorderStyle.FixedSingle; 
     int x = width + margin; 
     l.Location = new Point(0, 5); 
     l.Size = new Size(width, 20); 
     this.Controls.Add(l); 

     for (int i = 1; i <= 9; i++) 
     { 
      l = new Label(); 
      l.BackColor = Color.Red; 
      l.BorderStyle = BorderStyle.FixedSingle; 
      x += margin + width; 
      l.Location = new Point(x,5); 
      l.Size = new Size(width, 20); 
      this.Controls.Add(l); 
     } 
    } 

Image of executed code

+0

這是winforms嗎? WPF? – ryanyuyu

回答

0

看看這些行:

int x = width + margin; l.Location = new Point(0, 5);

在你的循環,每個按鈕被放置在:

l.Location = new Point(x, 5);

好像你剛剛輸入0你打算把x

0

這是因爲你在循環之前設置int x= width + margin。如果width = 10,那麼你將x設置爲11(緊跟在第一個標籤之後)。然後,在循環中,在放置第二個標籤之前,您再次將x增加到22,甚至在放置第二個標籤之前。

更改爲int x=0,我認爲你應該很好。

+0

謝謝!立即解決 – Chanter

0

這是因爲在循環中,在將寬度添加到x後設置了新標籤的位置。

如果你想寬度= 10,在循環開始X = 11,那麼你之前設置X + =保證金+寬度,這將使它22.所以,你的第二個標籤將被放置在x = 22

下迭代會很好,但你會看到第一個和第二個標籤之間的差距。

在循環開始之前嘗試設置x = 0。

希望有所幫助。

0

我覺得犯的錯誤之一是去下面一行:

'int width = (this.ClientSize.Width + margin - l.Size.Width) /10 ;' 

你把整個長度 - 一個元素的大小和10這實際上導致了寬度爲ClienSize.Width把它/ 11 我認爲以下一種更正確,並可能解決您的問題:

'int width = (this.ClientSize.Width + margin - l.Size.Width) /9 ;' 
'int width = (this.ClientSize.Width/10) - (margin*2) ;'