1

So I am nearing the end of my tasks in this particular set... I am trying to make an ellipse be drawn every time the timer ticks over. The timer has been enabled by default and the interval for each timer tick is 100ms. When I run the debugging, one ellipse is drawn on the canvas and no more - I have already tried a for-loop and a while-loop to set an arbitrary amount of ellipses to be drawn on each timer tick but that didn't work. Ideally I would like to create buttons that turn the timer on and off (I have a few ideas on how to do this, thanks to an earlier problem that was solved), I would like to get the code for the timer right first. Below is the code I have managed to get so far:

private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) 
         {
             Random^ rGen;
             timer1->Enabled = true;

             Graphics^ mainCanvas = CreateGraphics();

             // while loop to set upper limit for no# of ellipses
             // note: this is just for testing - would like to have
             // ellipses drawn automatically at random etc.
             int i = 0;
             while(i < 20)
             {
             rGen = gcnew Random();
             Brush^ greenBrush = gcnew SolidBrush(Color::Green);
             static int randX = rGen->Next(Width); //random x co-ordinate
             static int randY = rGen->Next(Height); //random y co-ordinate
             static int randWidth = rGen->Next(100); //random ellipse width
             static int randHeight = rGen->Next(100); //random ellipse height
             mainCanvas->FillEllipse(greenBrush, randX,randY,randWidth,randHeight);
             i++;
             }
         }

I am probably missing only one or two crucial things, I have also been learning C# and ASP.NET at the same time so my heads nearly exploding with so much being crammed into it. Any help is appreciated :).

4

2 回答 2

2
 static int randX = rGen->Next(Width);

static关键字是你的克星。在局部变量之前使用时,它确保变量只被初始化一次。因此,您只能绘制完全相同的椭圆。顺便说一句,使用调试器时很容易看到。

于 2012-07-21T11:38:06.857 回答
0

只是一个快速提示,请确保在此方法之外启用计时器,您可能已经这样做了,但在这里看不到,这可以确保您实际输入了该方法。正如@Hans 所说,删除静态。

于 2012-07-22T21:31:47.740 回答