110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Grid : UserControl
{
int m_GridX, m_GridY;
bool[,] cells;
public Grid() : this(15,15) // 默认225个方块。
{
}
public Grid(int gridX, int gridY)
{
m_GridX = gridX;
m_GridY = gridY;
cells = new bool[ gridY, gridX ];
}
protected override void OnPaintBackground(PaintEventArgs e)
{
}
protected override void OnPaint(PaintEventArgs e)
{
float cellWidth = (float)(ClientRectangle.Width-1) / m_GridX;
float cellHeight = (float)(ClientRectangle.Height-1) / m_GridY;
Bitmap memoryBmp = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
using (Graphics g = Graphics.FromImage(memoryBmp))
{
g.Clear( SystemColors.Control );
for (int y = 0; y <= m_GridY; y++)
{
for (int x = 0; x <= m_GridX; x++)
{
g.DrawLine(Pens.LightBlue, 0, y * cellHeight, ClientRectangle.Width, y * cellHeight);
g.DrawLine(Pens.LightBlue, x * cellWidth, 0, x * cellWidth, ClientRectangle.Height);
}
}
for (int y = 0; y < cells.GetLength(0); y++)
{
for (int x = 0; x < cells.GetLength(1); x++)
{
if (cells[y, x])
{
g.FillRectangle(Brushes.LightBlue, x * cellWidth, y * cellHeight, cellWidth, cellHeight);
}
}
}
}
e.Graphics.DrawImageUnscaled(memoryBmp, 0, 0);
memoryBmp.Dispose();
}
protected override void OnMouseClick(MouseEventArgs e)
{
float cellWidth = (float)(ClientRectangle.Width-1) / m_GridX;
float cellHeight = (float)(ClientRectangle.Height-1) / m_GridY;
int x = (int)(e.X / cellWidth);
int y = (int)(e.Y / cellHeight);
cells[y, x] = !cells[y, x];
Invalidate();
}
}