簡體   English   中英

Windows窗體顏色變化

[英]Windows Form color changing

所以我試圖將MasterMind程序作為一種練習。

  • 40個圖片框的領域(4行,10行)
  • 6個按鈕(紅色,綠色,橙色,黃色,藍色,紫色)

當我按下其中一個按鈕(假設紅色按鈕)時,圖片框變為紅色。
我的問題是我如何迭代所有這些圖片框?
我可以讓它工作,但只有我寫:
而且這種情況無法寫出來,這將帶給我無數基本相同的線條。

        private void picRood_Click(object sender, EventArgs e)
    {
        UpdateDisplay();
        pb1.BackColor = System.Drawing.Color.Red;
    }

按紅色按鈕 - >第一個圖片框變為紅色
按藍色按鈕 - >第二個圖片框變為藍色
按橙色按鈕 - >第三個圖片框變為橙色
等等...

我有一個以前類似的程序,模擬交通信號燈,我可以為每種顏色(紅色0,橙色1,綠色2)分配一個值。
是否需要類似的東西,或者我如何確切地對齊所有這些圖片框並使它們與正確的按鈕相對應。

最好的祝福。

我不會使用控件,而是可以使用單個PictureBox並處理Paint事件。 這使您可以在PictureBox內部繪制,以便快速處理所有框。

在代碼中:

// define a class to help us manage our grid
public class GridItem {
    public Rectangle Bounds {get; set;}
    public Brush Fill {get; set;}
}

// somewhere in your initialization code ie: the form's constructor
public MyForm() {
    // create your collection of grid items
    gridItems = new List<GridItem>(4 * 10); // width * height
    for (int y = 0; y < 10; y++) {
        for (int x = 0; x < 4; x++) {
            gridItems.Add(new GridItem() {
                Bounds = new Rectangle(x * boxWidth, y * boxHeight, boxWidth, boxHeight),
                Fill = Brushes.Red // or whatever color you want
            });
        }
    }
}

// make sure you've attached this to your pictureBox's Paint event
private void PictureBoxPaint(object sender, PaintEventArgs e) {
    // paint all your grid items
    foreach (GridItem item in gridItems) {
        e.Graphics.FillRectangle(item.Fill, item.Bounds);
    }
}

// now if you want to change the color of a box
private void OnClickBlue(object sender, EventArgs e) {
    // if you need to set a certain box at row,column use:
    // index = column + row * 4
    gridItems[2].Fill = Brushes.Blue; 
    pictureBox.Invalidate(); // we need to repaint the picturebox
}

我會使用面板作為所有圖片框的容器控件,然后:

foreach (PictureBox pic in myPanel.Controls)
{
    // do something to set a color
    // buttons can set an enum representing a hex value for color maybe...???
}

我不會使用picturebox,而是使用單個圖片框,使用GDI直接繪制到它上面。 結果要快得多,它會讓你編寫更復雜的游戲,包括精靈和動畫;)

這很容易學習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM