【问题标题】:How to draw an ellipse in a form when clicking in the form?点击表单时如何在表单中绘制椭圆?
【发布时间】:2019-01-15 10:01:27
【问题描述】:

我知道这听起来很简单,但我从未使用过 Visual Studio,我就是无法理解。我正在使用

private void Usecasediagram_Paint_elipse(object sender, PaintEventArgs e)
{
    System.Drawing.Graphics graphicsObj;

    graphicsObj = this.CreateGraphics();

    Pen myPen = new Pen(System.Drawing.Color.Green, 5);
    Rectangle myRectangle = new Rectangle(100, 100, 250, 200);
    graphicsObj.DrawEllipse(myPen, myRectangle);
}

在代码运行时绘制这个椭圆,但我希望它仅在我单击表单中的某个位置时出现,并且这个圆圈出现在鼠标位置。我已经让表单的 click 方法正常工作,但我不知道如何调用该函数,比如在 PaintEventArgs 中传递什么...

【问题讨论】:

标签: c# winforms visual-studio graphics


【解决方案1】:

在表单/类级别存储有关您要绘制的内容的信息,并使用Paint() Event 通过e.Graphics 提供自己的Graphics

如果你想要一个椭圆,那么:

public partial class Form1 : Form
{

    private Point DrawEllipseAt;
    private bool DrawEllipse = false;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Paint += Form1_Paint1;
        this.Click += Form1_Click;
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        this.DrawEllipseAt = this.PointToClient(Cursor.Position);
        this.DrawEllipse = true;
        this.Invalidate();
    }

    private void Form1_Paint1(object sender, PaintEventArgs e)
    {
        if (this.DrawEllipse)
        {
            Graphics G = e.Graphics;
            Rectangle myRectangle = new Rectangle(DrawEllipseAt, new Size(0, 0));
            myRectangle.Inflate(new Size(125, 100));
            using (Pen myPen = new Pen(System.Drawing.Color.Green, 5))
            {
                G.DrawEllipse(myPen, myRectangle);
            }
        }
    }

}

如果你想要多个省略号:

public partial class Form1 : Form
{

    private List<Point> DrawEllipsesAt = new List<Point>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Paint += Form1_Paint1;
        this.Click += Form1_Click;
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        this.DrawEllipsesAt.Add(this.PointToClient(Cursor.Position));
        this.Invalidate();
    }

    private void Form1_Paint1(object sender, PaintEventArgs e)
    {
        Graphics G = e.Graphics;
        if (this.DrawEllipsesAt.Count > 0)
        {
            using (Pen myPen = new Pen(System.Drawing.Color.Green, 5))
            {
                foreach (Point pt in this.DrawEllipsesAt)
                {
                    Rectangle myRectangle = new Rectangle(pt, new Size(0, 0));
                    myRectangle.Inflate(new Size(125, 100));
                    G.DrawEllipse(myPen, myRectangle);
                }
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多