【问题标题】:How to change color of ellipse when new ellipse is draw in a timer in C#在 C# 中的计时器中绘制新椭圆时如何更改椭圆的颜色
【发布时间】:2019-11-21 20:05:36
【问题描述】:

我有一个绘制椭圆的函数。当通过更改表单大小绘制新椭圆时,我想通过将其颜色更改为与其背景相同的颜色来使先前绘制的椭圆不可见。

这是我在课堂上的功能:

class ClassClock
{
    public static void drawClock(Point m, int s, Form frm, Color myColor) 
    {
        Graphics paper = frm.CreateGraphics();
        Pen myPen = new Pen(myColor);

        int w = frm.ClientSize.Width;
        int h = frm.ClientSize.Height;
        m = new Point(w / 2, h / 2);
        s = Math.Min(w, h) / 2;

        paper.DrawEllipse(myPen, m.X - s, m.Y - s, s * 2, s * 2);
    }
}

这是我的计时器:

private void timer1_Tick(object sender, EventArgs e)
{
    ClassClock.drawClock(m, s, this, this.BackColor);
    ClassClock.drawClock(m, s, this, Color.Black);
}

有人可以帮我找到解决办法吗?

【问题讨论】:

  • 您必须引用旧椭圆才能对其进行任何操作。
  • 您需要在Paint 事件处理程序中擦除旧椭圆并绘制新椭圆,而不是在Tick 中。您的 Tick 处理程序应使新旧椭圆区域无效。

标签: c# drawing paint ellipse


【解决方案1】:

你不应该像这样使用CreateGraphics。相反,请覆盖表单的 OnPaint 方法并在该方法中完成所有绘画。

Windows 使用即时模式图形系统。这意味着一旦你的椭圆被绘制出来,它就消失了,除了屏幕上当前的像素。如果窗口被最小化或另一个窗口被拖过它,椭圆将消失并且必须重新绘制。这就是OnPaint 方法的用途。

这是一个简单的表单,可在单击按钮时更改圆圈的颜色。要运行此代码,您需要在表单中添加一个按钮并将其命名为 btnChangeColor

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //Property to hold the current color.  This could be a private field also.
    public Color CurrentColor { get; set; } = Color.Red;

    //Used to generate a random number when the button is clicked.
    private Random rnd = new Random();

    //All painting of the form should be in this method.
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        //Use the graphics event provided to you in PaintEventArgs
        Graphics paper = e.Graphics;

        int w = this.ClientSize.Width;
        int h = this.ClientSize.Height;
        Point m = new Point(w / 2, h / 2);
        int s = Math.Min(w, h) / 2;

        //It is important to dispose of any pens you create
        using (Pen myPen = new Pen(CurrentColor))
        {
            paper.DrawEllipse(myPen, m.X - s, m.Y - s, s * 2, s * 2);
        }
    }

    //When the button is clicked, the `CurrentColor` property is set to a random
    //color and the form is refreshed to get it to repaint itself.
    private void btnChangeColor_Click(object sender, EventArgs e)
    {
        //Change the current color
        CurrentColor = Color.FromArgb(255, rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));

        //Refresh the form so it repaints itself
        this.Refresh();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2014-05-18
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多