【问题标题】:I made a rectangle how do I check if the mouse clicked on it?我做了一个矩形如何检查鼠标是否点击它?
【发布时间】:2016-07-12 02:30:02
【问题描述】:

如何检查鼠标是否点击了矩形?

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

【问题讨论】:

  • 你的gfx指的是什么?
  • 如果你的“gfx”是表单中的“e.Graphics...”,那么只需使用事件MouseDown,有e.X和e.Y.
  • 永远不要使用control.CreateGraphics!永远不要尝试缓存 Graphics 对象!使用Graphics g = Graphics.FromImage(bmp) 或在控件的Paint 事件中使用e.Graphics 参数绘制到Bitmap bmp 中。

标签: c# windows-forms-designer hittest drawrectangle


【解决方案1】:

如果您的“gfx”是来自表单的“e.Graphics...”,则只是一个快速而肮脏的示例:

  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 有几个方便但经常被忽视的功能。在这种情况下使用Rectangle.Contains(Point) 函数是最好的解决方案:

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

    要确定您是否点击了轮廓,您需要确定宽度,因为用户无法轻松点击单个像素。

    为此,您可以使用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 
    
    }
    

    ..或坚持矩形..:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多