简体   繁体   English

单击一个形状WinForm

[英]Click in a shape WinForm

I am drawing a circle of _radius = 50 pixels in the center of the form: 我在窗体的中心绘制了一个_radius = 50像素的圆:

g.FillEllipse(Brushes.Red, this.ClientRectangle.Width / 2 - _radius / 2, this.ClientRectangle.Height / 2 - _radius / 2, _radius, _radius);

Now I want to check if the user clicked in the form. 现在,我要检查用户是否单击了表单。

if (e.Button == MouseButtons.Left)
{
    int w = this.ClientRectangle.Width;
    int h = this.ClientRectangle.Height;

    double distance = Math.Sqrt((w/2 - e.Location.X) ^ 2 + (h/2 - e.Location.Y) ^ 2);
    ....

 if (distance <_radius)
    return true;
 else
    return false;
}

Now I am ending up with wrong values. 现在,我最终得到了错误的值。 For instance if I click on the edge of the circle I at times get distance of ~10 or NaN at times. 例如,如果我单击圆的边缘,则有时会得到〜10或NaN的距离。 What am I doing wrong here? 我在这里做错了什么?

  1. You're performing integer division, which is coarser than floating-point division. 您正在执行整数除法,它比浮点除法更粗糙。
  2. ^ is not the "power-to" operator, it's the bitwise XOR operator , which is probably not what you want. ^不是“ power-to”运算符, 它是按位XOR运算符 ,可能不是您想要的。 Use Math.Pow or x*x instead. 请改用Math.Powx*x
  3. You can simplify the last statement by simply doing return distance < _radius . 您只需执行return distance < _radius即可简化最后一条语句。

Try this: 尝试这个:

Single w = this.ClientRectangle.Width;
Single h = this.ClientRectangle.Height;

Single distanceX = w / 2f - e.Location.X;
Single distanceY = h / 2f - e.Location.Y;

Single distance = Math.Sqrt( distanceX  * distanceX + distanceY * distanceY );

return distance < this._radius;

(This code does not change any assumptions about the location of the circle). (此代码不会更改有关圆的位置的任何假设)。

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

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