I made a rectangle how do I check if the mouse clicked on it?

别来无恙 提交于 2019-12-12 02:12:42

问题


How do I check if a mouse clicked a rectangle?

Graphics gfx;
Rectangle hitbox;
hitbox = new hitbox(50,50,10,10);
//TIMER AT THE BOTTOM
gfx.Draw(System.Drawing.Pens.Black,hitbox);

回答1:


Just a sample quick and dirty, if your "gfx" is a "e.Graphics..." from a Form:

  public partial class Form1 : Form
  {
    private readonly Rectangle hitbox = new Rectangle(50, 50, 10, 10);
    private readonly Pen pen = new Pen(Brushes.Black);

    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawRectangle(pen, hitbox);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
      if ((e.X > hitbox.X) && (e.X < hitbox.X + hitbox.Width) &&
          (e.Y > hitbox.Y) && (e.Y < hitbox.Y + hitbox.Height))
      {
        Text = "HIT";
      }
      else
      {
        Text = "NO";
      }
    }
  }



回答2:


Rectangle has several handy but often overlooked functions. In this case using the Rectangle.Contains(Point) function is the best solution:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (hitbox.Contains(e.Location)) ..  // clicked inside
}

To determine if you clicked on the outline you will want to decide on a width, since the user can't easily hit a single pixel.

For this you can use either GraphicsPath.IsOutlineVisible(Point)..

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    GraphicsPath gp = new GraphicsPath();
    gp.AddRectanle(hitbox);
    using (Pen pen = new Pen(Color.Black, 2f))
      if (gp.IsOutlineVisible(e.location), pen)  ..  // clicked on outline 

}

..or stick to rectangles..:

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    Rectangle inner = hitbox;
    Rectangle outer = hitbox;
    inner.Inflate(-1, -1);  // a two pixel
    outer.Inflate(1, 1);    // ..outline

    if (outer.Contains(e.Location) && !innerContains(e.Location)) .. // clicked on outline
}


来源:https://stackoverflow.com/questions/38319092/i-made-a-rectangle-how-do-i-check-if-the-mouse-clicked-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!