我需要在winform上绘制两种不同颜色(红色和蓝色)的动态矩形(10,10)。它的数量可能超过100,000+。
当我在winform或面板上绘制它们时,它们开始重叠。我试过滚动条,但我无法做到。当我垂直滚动它们时,形状开始变得混乱。矩形的数量可以很多(行和列)。
private void button1_Click(object sender, EventArgs e)
{
tabControl2.Visible = true;
Graphics g = FileInfoTab.CreateGraphics();
Pen p = new Pen(Color.Black);
for (int y = 158; y < 1000; y += 15)
{
for (int x = 120; x < 280; x += 15)
{
Random rd = new Random();
int nm = rd.Next(0, 10);
if (nm % 2 == 0) //if number is even draw red rectangle else blue rectangle
{
SolidBrush sb = new SolidBrush(Color.Red);
g.DrawRectangle(p, x, y, 10, 10);
g.FillRectangle(sb, x, y, 10, 10);
//x += 15;
}
else
{
SolidBrush sb_1 = new SolidBrush(Color.Blue);
g.DrawRectangle(p, x, y, 10, 10);
g.FillRectangle(sb_1, x, y, 10, 10);
}
}
}
}
答案 0 :(得分:0)
从Graphics
创建的Control.CreateGraphics()
对象必须始终在您的代码退出之前处理,如下所述:(CreateGraphics() Method and Paint Event Args)
也许您应该考虑使用FileInfoTab.Paint事件:
private Bitmap Surface;
private Graphics g;
private void button1_Click(object sender, EventArgs e)
{
RedrawSurface();
}
private void RedrawSurface()
{
tabControl2.Visible = true;
Surface = new Bitmap(FileInfoTab.Width, FileInfoTab.Height, PixelFormat.Format24bpprgb);
g = Graphics.FromImage(Surface);
Pen p = new Pen(Color.Black);
for (int y = 158; y < 1000; y += 15)
{
for (int x = 120; x < 280; x += 15)
{
Random rd = new Random();
int nm = rd.Next(0, 10);
if (nm % 2 == 0)
{
SolidBrush sb = new SolidBrush(Color.Red);
g.DrawRectangle(p, x, y, 10, 10);
g.FillRectangle(sb, x, y, 10, 10);
//x += 15;
}
else
{
SolidBrush sb_1 = new SolidBrush(Color.Blue);
g.DrawRectangle(p, x, y, 10, 10);
g.FillRectangle(sb_1, x, y, 10, 10);
}
}
}
g.Dispose();
FileInfoTab.Invalidate();
}
private void FileInfoTab_Paint(object sender, PaintEventArgs e)
{
if (Surface != null)
{
e.Graphics.DrawImage(Surface, 0, 0);
}
}