簡體   English   中英

如何使用計時器隨機更改畫筆顏色?

[英]How do I change Brush color randomly using a timer?

我的 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;
        }
    }

在表單級別聲明 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));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM