본문 바로가기

프로그래밍

[C# 그리고 GDI+] Rectangle 배열과 ArrayList를 이용한 간단한 코드

Rectangle 클래스를 이용하여 2차원 배열을 생성하고 9개의 사각형을 그렸다.

또한 클릭된 사각형의 개수를 세기 위해, ArrayList를 생성하여 index를 저장하도록 하였다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Drawing.Drawing2D;
namespace SETProject
{
    public partial class Form1 : Form
    {      
        private Rectangle[,] rect;
        private int cardW = 100, cardH = 140;
        private ArrayList selCard;
        public Form1()
        {
            InitializeComponent();
            rect = new Rectangle [3,3];
            selCard = new ArrayList();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
           
        }
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
        }
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            Graphics g = this.CreateGraphics();
          
            for(int i=0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                {
                    Point p = new Point(i, j);
                    if (rect[i, j].Contains(e.X, e.Y))
                    {
                        if (selCard.Contains(p))
                        {
                            selCard.Remove(p);
                            g.DrawRectangle(Pens.Black, rect[i, j]);
                            return;
                        }
                        g.DrawRectangle(Pens.Pink, rect[i, j]);
                        selCard.Add(p);
                    }
                }
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            int x = 70, y = 70;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    rect[i, j] = new Rectangle(x, y, cardW, cardH);
                    Graphics g = e.Graphics;
                    g.DrawRectangle(Pens.Black, rect[i,j]);
                    x +=130;
                }
                y+=170;
                x = 70;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < selCard.Count; i++)
            {
                Console.Write(selCard[i]);
                Console.WriteLine("\n");
            }
        }
    }
}