日期:2014-05-18 浏览次数:20937 次
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() {