2017-06-21 58 views
0

我画的_radius = 50像素的圆圈形式的中心:单击形状的WinForm

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

现在我要检查,如果用户在点击的形式。

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; 
} 

现在我结束了错误的值。例如,如果我点击圆圈的边缘,有时会得到〜10或NaN的距离。我在这里做错了什么?

+0

^运算符不会做你认为它所做的事情,请使用Math.Pow()。一般不这样做,你会喜欢GraphicsPath。用它的IsVisible()方法绘制并进行命中测试。 –

回答

3
  1. 您正在进行整数除法,这比浮点除法粗糙。
  2. ^不是“权力”运营商it's the bitwise XOR operator,这可能不是你想要的。改为使用Math.Powx*x
  3. 只需简单地做return distance < _radius即可简化上一条语句。

试试这个:

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; 

(此代码并不会改变对圆的位置的任何假设)。

+0

上面的代码为我提供了半径为100的距离,当我点击圆的表面时。我在这里错过简单的东西吗? –

+0

@SanjnaMalpani相对于圆的左上角,窗体或其他东西是否有'e.Location.X'和'.Y'? – Dai

+0

对不起,我愚蠢。我在半径和直径之间感到困惑。很好,谢谢 –