使用以下代码在图片框中绘制多个矩形时,它会闪烁 我该怎么办呢?
private void drawRect(int sx, int sy, int ex, int ey, int w, int h)
{
Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black));
//Top ok
pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, 0, w, sy);
//Bottom
pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, ey, w, h);
//Left ok
pictureBox1.CreateGraphics().FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
//Right
pictureBox1.CreateGraphics().FillRectangle(cloud_brush, ex, sy, w, ey - sy);
}
答案 0 :(得分:1)
您正在为每个绘制操作使用CreateGraphics()
,但您只需创建一次。 CreateGraphics()
很慢,所以这会加速你的代码。
private void drawRect(int sx, int sy, int ex, int ey, int w, int h)
{
using (Graphics g = CreateGraphics())
using (Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black)))
{
//Top ok
g.FillRectangle(cloud_brush, 0, 0, w, sy);
//Bottom
g.FillRectangle(cloud_brush, 0, ey, w, h);
//Left ok
g.FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
//Right
g.FillRectangle(cloud_brush, ex, sy, w, ey - sy);
}
}
它闪烁的原因是使用CreateGraphics。 我建议你改用paint事件。
private void drawRect(Graphics g, int sx, int sy, int ex, int ey, int w, int h)
{
using (Brush cloud_brush = new SolidBrush(Color.FromArgb(80, Color.Black)))
{
//Top ok
g.FillRectangle(cloud_brush, 0, 0, w, sy);
//Bottom
g.FillRectangle(cloud_brush, 0, ey, w, h);
//Left ok
g.FillRectangle(cloud_brush, 0, sy, sx, ey - sy);
//Right
g.FillRectangle(cloud_brush, ex, sy, w, ey - sy);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
drawRect(e.Graphics,80, 190, 160, 140, 100, 130);
}