简体   繁体   中英

How to draw rectangle by coordinates of click?

I have pictureBox click event. I get coordinates of click and try t draw circle:

  private void pictureMain_Click(object sender, EventArgs e){

    MouseEventArgs me = (MouseEventArgs)e;

    Point coordinates = me.Location;
    int x = coordinates.X;
    int y = coordinates.Y;

    // Create pen.
    Pen blackPen = new Pen(Color.Red, 2);

    // Create rectangle for ellipse.
    Rectangle rect = new Rectangle(x, y, 50, 50);

    g.DrawEllipse(blackPen, rect);

    }

But it draws circle not in coordinates(x,y) of picturebox. It places circle in another place.

Try this:

private void pictureBox1_Click (object sender, EventArgs e)
{
    Point ellipseCenter = ((MouseEventArgs) e).Location;
    Size  ellipseSize   = new Size (50, 50);

    Point rectPosition = new Point (ellipseCenter.X - ellipseSize.Width / 2, ellipseCenter.Y - ellipseSize.Height / 2);
    Rectangle rect = new Rectangle (rectPosition, ellipseSize);

    using (Graphics grp = Graphics.FromImage (pictureBox1.Image))
    {
        grp.DrawEllipse (Pens.Red, rect);
    }

    pictureBox1.Refresh ();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM