2017-06-21 59 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

對不起,我愚蠢。我在半徑和直徑之間感到困惑。很好,謝謝 –