Question

I am looking to draw an ellipse on the screen during the MouseMove() event but am wanting it to only draw the most recent ellipse from a start point to the current mouse position. At the moment it is drawing an ellipse for every mouse position that is getting registered. I would be able to draw it easily enough without showing the ellipse if i simply used the MouseDown() and MouseUp() events, but I am wanting the user to be able to see the ellipse as they move the mouse around, so they can know exactly where they are placing it. Does anyone know how I could achieve this?

My current code is as follows:

private void pnlDraw_MouseDown(object sender, MouseEventArgs e)
{
    initialX = e.X;
    initialY = e.Y;
    previousX = e.X;
    previousY = e.Y;
    isPainting = true;
}

private void pnlDraw_MouseMove(object sender, MouseEventArgs e)
{
    if (isPainting)
    {
        switch (currentDrawType)
        {

            case DRAWTYPE.ELLIPSE:
            {
                DrawEllipse(e);
                break;
            }
            default:
            {
                break;
            }
        }
    }
}

private void DrawEllipse(MouseEventArgs e)
{
    pen = new Pen(Color.Black);
    Graphics graphics = pnlDraw.CreateGraphics();
    graphics.DrawEllipse(pen, initialX, initialY, e.X - initialX, e.Y - initialY);

    previousX = e.X;
    previousY = e.Y;
    graphics.Dispose();
}

Any help would be greatly appreciated!

Was it helpful?

Solution

The first thing you should do when you are drawing something on screen is to clear what was previously displayed. Otherwise, you simply draw on top of existing drawing.

In WinForm, it's normally handled in the OnBackgroundPaint() method, which is a simple way of saying that it's there you should clear the background.

It should looks like this:

e.Graphics.FillRectangle(new SolidBrush(MyBackgroundColor), e.ClipRectangle);

or if it's not a drawing event:

graphics.FillRectangle(new SolidBrush(MyBackgroundColor), 0, 0, MyWidth, MyHeight);

And should be called before drawing anything on top of it. It is also a guaranty that your drawing zone is ready to be drawn on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top