问题描述
您好,我正在尝试在Windows窗体上绘制一个棋盘格图案.我正在使用以下代码,但这意味着只要重新绘制窗口(例如将鼠标悬停在按钮上),就会导致图案被重新绘制和闪烁.有没有更好的方法来实现这一目标?
绘制棋盘格的代码是:
Hi, I am trying to draw a checkerboard pattern onto my windows form. I am using the following code but it means that whenever the window gets repainted (e.g. hover over a button) it causes the pattern to be redrawn and flicker. Is there a better way to achieve this?
The code to draw the checkerboard is:
private void drawBoard(Graphics g) {
bool dark = true;
for (int i = 0; i < 8; i++) {
dark = !dark;
for (int j = 0; j < 8; j++) {
dark = !dark;
Pen blackPen = new Pen(Color.Black, 2);
SolidBrush brush;
if (dark) {
brush = new SolidBrush(Color.LightGray);
} else {
brush = new SolidBrush(Color.Gray);
}
int x = 50 * i + 10;
int y = 50 * j + 10;
int width = 50;
int height = 50;
// Draw rectangle to screen.
g.DrawRectangle(blackPen, x, y, width, height);
g.FillRectangle(brush, x, y, width, height);
}
}
}
调用Paint事件处理程序时,主要形式只是调用此函数.
The main form just calls this function when the Paint event handler is called.
推荐答案
internal class MyControl : Control {
internal MyControl() { DoubleBuffered = true; }
//...
}
另外,与闪烁无关,但有助于提高性能:更改图形中的某些内容时,要触发控件的Paint
事件,您将需要调用Control.Invalidate
.代替通常没有参数的Invalidate
,将Invalidate
与参数一起使用,可使您仅使场景的修改部分无效.
帮个忙,使用自定义Control
进行绘画(如上所示,属于子类),而不是Form
.使用Form
,您将失去灵活性.
Also, something not related to flicker, but helpful to improve performance: when you change something in graphics, to trigger control''s Paint
event you will need to call Control.Invalidate
. Instead of usual parameter-less Invalidate
use Invalidate
with parameters, which allows you to invalidate only a modified part of the scene.
Do yourself a favor, use custom Control
for painting (sub-classed as I show above), not Form
. With Form
you loose bit chunk of flexibility.
这篇关于如何绘制棋盘格图案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!