我有一个图片框,我想以固定的速度绘制(例如60次/秒,60fps)。经过几个小时的谷歌搜索,我唯一能找到的信息是在定时器中使用Invalidate()方法来固定控件的重绘速度......(duh)。我也想这么做,但问题是画框上的Paint事件已经在程序启动时被自己不断调用了。这当然会占用很多额外的cpu。我如何才能阻止它自动发射?
class Block {
public bool alive;
public Block(bool alive) {
this.alive = alive;
}
}
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
int w;
int width;
int height;
Bitmap myBitmap;
Block[,] block;
Block[,] buffer;
private void Form2_Load(object sender, EventArgs e) {
myBitmap = new Bitmap(Width, Height);
w = 3;
width = 700 / w;
height = 400 / w;
initblocks();
}
private void initblocks() {
block = new Block[width, height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
block[x, y] = new Block(false);
}
}
}
private void randomizeBlocks() {
Random r = new Random();
buffer = new Block[width, height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
buffer[x, y] = new Block((r.Next(2) == 0));
}
}
block = buffer;
}
protected void pictureBox1_Paint(object sender, PaintEventArgs e) {
randomizeBlocks();
Graphics g = Graphics.FromImage(myBitmap);
Pen pen = new Pen(Color.Black);
//draw the blocks
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
try {
if (block[x, y].alive) {
g.FillRectangle(Brushes.Black, x * w, y * w, w, w);
}
} catch (Exception) {
Console.WriteLine("Draw blocks error");
}
}
}
//draw the grid
for (int y = 0; y < height + 1; y++) {
g.DrawLine(pen, 0, y * w, width * w, y * w);
}
for (int x = 0; x < width + 1; x++) {
g.DrawLine(pen, x * w, 0, x * w, height * w);
}
//finish up
pictureBox1.Image = myBitmap;
myBitmap = new Bitmap(Width, Height);
pen.Dispose();
g.Dispose();
}