110,538
社区成员
发帖
与我相关
我的任务
分享
public partial class Form7 : Form
{
// 定义方块的宽度、高度和间距。
const int BLOCK_WIDTH = 80, BLOCK_HEIGHT = 30, BLOCK_SPACE = 2;
Block[,] _blocks;
public Form7()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Initialize();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
if (_blocks != null)
{
Rectangle rect = e.ClipRectangle;
Point offset = panel1.AutoScrollPosition;
// 根据滚动条的位置进行调整
rect.Offset(-offset.X, -offset.Y);
// 计算出哪些方块需要重绘
int x0 = rect.Left / (BLOCK_WIDTH + BLOCK_SPACE);
int x1 = (rect.Right - 1) / (BLOCK_WIDTH + BLOCK_SPACE);
int y0 = rect.Top / (BLOCK_HEIGHT + BLOCK_SPACE);
int y1 = (rect.Bottom - 1) / (BLOCK_HEIGHT + BLOCK_SPACE);
for (int y = y0; y <= y1; y++)
{
for (int x = x0; x <= x1; x++)
{
Rectangle rectBlock = new Rectangle(
x * (BLOCK_WIDTH + BLOCK_SPACE) + BLOCK_SPACE,
y * (BLOCK_HEIGHT + BLOCK_SPACE) + BLOCK_SPACE,
BLOCK_WIDTH, BLOCK_HEIGHT);
rectBlock.Offset(offset);
// 绘制方块
RenderBlock(_blocks[y, x], rectBlock, e);
}
}
}
}
private void RenderBlock(Block block, Rectangle rect, PaintEventArgs e)
{
Color backColor = block.Color;
Color foreColor = Color.FromArgb(
255 - backColor.R,
255 - backColor.G,
255 - backColor.B);
Brush br;
// 绘制渐变底色
br = new System.Drawing.Drawing2D.LinearGradientBrush(
rect, Color.White, backColor, 45f);
e.Graphics.FillRectangle(br, rect);
br.Dispose();
// 绘制文字
br = new SolidBrush(foreColor);
TextRenderer.DrawText(e.Graphics,
string.Format("x={0},y={1}", block.X + 1, block.Y + 1),
panel1.Font,
rect, foreColor);
br.Dispose();
// 绘制边框
Pen pen = new Pen(backColor);
e.Graphics.DrawRectangle(pen,
rect.X, rect.Y, rect.Width - 1, rect.Height - 1);
pen.Dispose();
}
class Block
{
public int X { get; set; }
public int Y { get; set; }
public Color Color { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
Initialize();
}
private void Initialize()
{
// 按界面控件指定的值初始化存储方块的二维数组
_blocks = CreateBlocks((int)numericUpDown1.Value, (int)numericUpDown2.Value);
// 根据方块的行列数和方块的大小,计算虚拟空间的大小,以此来为Panel产生滚动条。
Size size = new System.Drawing.Size(
_blocks.GetLength(1) * (BLOCK_WIDTH + BLOCK_SPACE),
_blocks.GetLength(0) * (BLOCK_HEIGHT + BLOCK_SPACE));
panel1.AutoScroll = true;
panel1.AutoScrollMinSize = size;
// 所有初始化工作完成后,通知Panel控件进行重绘。
panel1.Invalidate();
}
private Block[,] CreateBlocks(int columnCount, int rowCount)
{
Block[,] array = new Block[rowCount, columnCount];
Random rnd = new Random();
for (int y = 0; y < rowCount; y++)
{
for (int x = 0; x < columnCount; x++)
{
Block block = new Block();
block.X = x;
block.Y = y;
block.Color = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
array[y, x] = block;
}
}
return array;
}
}