2

c#で25個の長方形(5*5)を描画する最良の方法は何でしょうか? 後で特定の四角形に到達してその色を変更できるようにする必要があります。たとえば、ユーザーが間違った単語を入力した場合に色を赤に変更します。この場合、長方形の配列を作成する方が適切でしょうか?

これは私がこれまでに持っているものです

Graphics g = pictureBox1.CreateGraphics();

int x =0;
int y= 0;
int width = 20;
int height = 20;
for (int i = 0; i < 25; i++)
{
    if (i <= 4)
    {
        g.FillRectangle(Brushes.Blue, x, y, width, height);
        x += 50;
    }
    else if (i > 4)
    {
        y = 50;
        g.FillRectangle(Brushes.Blue, x, y, width, height);
        x += 50;
    }
}
4

2 に答える 2

1

これは、完全なコードではなく、開始する必要があります。PictureBox コントロールを追加し、デフォルト名 (picurebox1) を使用する必要があります。編集:ボタンも追加する必要があります:)

public partial class Form1 : Form
{
    public List<Rectangle> listRec = new List<Rectangle>();
    Graphics g;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Rectangle rect = new Rectangle();
        rect.Size = new Size(100,20);
        for (int x = 0; x < 5; x++)
        {
            rect.X = x * rect.Width;
            for (int y = 0; y < 5; y++)
            {
                rect.Y = y * rect.Height;
                listRec.Add(rect);
            }
        }

        foreach (Rectangle rec in listRec)
        {
            g = pictureBox1.CreateGraphics();
            Pen p = new Pen(Color.Blue);
            g.DrawRectangle(p, rec);
        }
    }

    public void ChangeColor(Rectangle target, Color targetColor)
    {
        Pen p = new Pen(targetColor);
        g.DrawRectangle(p, target.X, target.Y, target.Width, target.Height);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.D0: ChangeColor(listRec[0], Color.Red);
                break;
            case Keys.D1: ChangeColor(listRec[1], Color.Red);
                break;
            //..more code to handle all keys..
        }
    }    
}
于 2012-11-28T00:55:59.947 に答える
0

パフォーマンスや外観に関心がない場合、最も簡単なアプローチは、コメントの1つに記載されているように、Form_Loadイベントにパネルのリストのリストを作成することです。

List<List<Panel>> panelGrid = new List<List<Panel>>();
for (var i = 0; i < 5; i++)
{  
    var panelRow = new List<Panel>();
    for (var j = 0; j < 5; j++)
    {
        panelRow.Add(new Panel());

        // add positioning logic here
    }

    panelGrid.Add(panelRow);
}

そうすれば、後の段階で個々の個人を参照できるようになります...

Graphicsクラス(より良いアプローチ)を使用する必要がある場合は、同様の設定を行う必要がありますが、Panelを独自のクラスに置き換えます。次に、Form_Paintイベントで、オブジェクトのリストを反復処理してレンダリングします。

class MyPanel
{
    public Size size;
    public Color color;
}

...

foreach (var myPanelRow in myPanelGrid)
    foreach (var myPanel in myPanelRow)
        g.FillRectangle(myPanel.color, myPanel.size); // this obviously won't work as is, but you get the idea

次に、色を変更する必要がある場合は、次のようにします。

myPanelsGrid[0][0].color = Color.Blue;
myForm.Invalidate();

2行目は、イベントでペイントが再度呼び出される結果になります。

于 2012-11-28T00:54:44.343 に答える