简体   繁体   English

如何通过点击坐标绘制矩形?

[英]How to draw rectangle by coordinates of click?

I have pictureBox click event. 我有pictureBox单击事件。 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. 但是它不在画框的坐标(x,y)中绘制圆。 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 ();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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