在 Windows 窗体应用程序中创建新对象时,如何防止以前绘制的对象消失? [英] How do I keep previously painted objects from disappearing when a new one is creating in a Windows Form Application?

查看:25
本文介绍了在 Windows 窗体应用程序中创建新对象时,如何防止以前绘制的对象消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,在我的 Windows 窗体应用程序中,每次在特定图片框中单击鼠标时,我都想绘制一个椭圆,并且我希望以前绘制的椭圆保留在图片框中.

My problem is that within my Windows Form Application, I want to draw an Ellipse everytime the mouse is clicked within a specific picture box, and I want the previously drawn ellipses to remain present in the picture box.

在当前状态下,一旦单击鼠标,先前绘制的椭圆将替换为在光标新位置绘制的新椭圆.

In its current state, once the mouse is clicked, the previously drawn ellipse will be replaced with the new one drawn at the cursor's new location.

Ball.Paint 绘制一个椭圆.

Ball.Paint draws an ellipse.

这是问题的相关代码:

    private Ball b;

    private void pbField_Paint(object sender, PaintEventArgs e)
    {
        if (b != null)
            b.Paint(e.Graphics);
    }

    private void pbField_MouseClick(object sender, MouseEventArgs e)
    {           
        int width = 10;
        b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width);
        Refresh();
    }

如果有更多需要的代码或信息,我可以提供.

If there is any more needed code or information I am able to provide it.

推荐答案

您需要某种数据结构来存储先前的省略号.一种可能的解决方案如下:

You need some sort of data structure to store prior ellipses. One possible solution is below:

private List<Ball> balls = new List<Ball>(); // Style Note:  Don't do this, initialize in the constructor.  I know it's legal, but it can cause issues with some code analysis tools.

private void pbField_Paint(object sender, PaintEventArgs e)
{
    if (b != null)
    {
        foreach(Ball b in balls)
        {
            b.Paint(e.Graphics);
        }
    }
}

private void pbField_MouseClick(object sender, MouseEventArgs e)
{           
    int width = 10;
    b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width);
    balls.Add(b);
    Refresh();
}

这篇关于在 Windows 窗体应用程序中创建新对象时,如何防止以前绘制的对象消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆