如何使用计时器随机更改画笔颜色?

时间:2019-01-09 16:32:14

标签: c# .net winforms gdi+

我的Winform中有一个椭圆,我试图随机更改其填充属性,即我希望椭圆的颜色不断变化。

SolidBrush colour;

 private void drawBorder()
    {
        Pen bPen = new Pen(Color.Black, 8);
        colour = new SolidBrush(Color.Yellow);

        g.DrawEllipse(bPen, 412, 269, 19, 19);
        g.FillEllipse(colour, 412, 269, 19, 19);

        timer1.Enabled = true;
        timer1.Start();
    }


private void timer1_Tick(object sender, EventArgs e)
    {
        //g.FillEllipse(colour, 412, 269, 19, 19);

        if (this.colour.Color == Color.Yellow)
        {
            //MessageBox.Show("!", Color.Yellow.ToString());
            this.colour.Color = Color.Pink;
        }
        if (this.colour.Color == Color.Pink)
        {
            //MessageBox.Show("#", this.colour.Color.ToString());
            this.colour.Color = Color.Yellow;
        }
    }

1 个答案:

答案 0 :(得分:3)

在窗体级别声明Random类,并使用Color.FromArgb函数创建颜色:

private Color colour = Color.Black;
private Random rnd = new Random();

private void timer1_Tick(object sender, EventArgs e) {
  colour = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
  this.Invalidate();
}

protected override void OnPaint(PaintEventArgs e) {      
  base.OnPaint(e);

  e.Graphics.Clear(Color.White);
  e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
  using (SolidBrush br = new SolidBrush(colour)) {
    e.Graphics.FillEllipse(br, new Rectangle(16, 16, 64, 64));
  }
}