2014-06-07 89 views
4

我想在android中創建一個類似pad的視圖。我得到了一個符合用戶手勢的圓圈,我正在使用距離來保持向外控制板主圈外的圓圈。 我的問題是我想讓圈子繼續跟着手勢,但留在主圈內。我使用公式來找到使用角度和半徑的點,但它確實有些時髦的東西。如何在另一個圓圈內保持一個圓形android view view控制

我翻譯畫布,使主圓心爲0,0。 下面是代碼:

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.translate(this.mainRadius, this.mainRadius); 

    canvas.drawCircle(0, 0, this.mainRadius, this.debugPaint); 
    canvas.drawCircle(this.handleX, this.handleY, this.handleRadius, this.handlePaint); 
} 

private void translateHandle(MotionEvent event) { 
    int x = (int) (event.getX() - this.mainRadius); 
    int y = (int) (event.getY() - this.mainRadius); 
    double distance = distanceFromCenter(x, y); 
    if (distance <= this.maxDistance) { 
     this.handleX = x; 
     this.handleY = y; 
    } else { 
     float angle = (float) Math.toDegrees(Math.atan2(y, x)); 
     if (angle < 0) 
      angle += 360; 

     this.handleX = (int) ((this.mainRadius - this.handleRadius) * Math.cos(angle)); 
     this.handleY = (int) ((this.mainRadius - this.handleRadius) * Math.sin(angle)); 
    } 

    //onTranslateHandle(distance); 
} 

這裏是一個gif圖片的時髦的東西:The issue animated

回答

3

我無法驗證此更改爲您的代碼片段,但希望它能提供一些想法,無論如何,

private void translateHandle(MotionEvent event) { 
    float x = event.getX() - this.mainRadius; 
    float y = event.getY() - this.mainRadius; 
    double distance = distanceFromCenter(x, y); 
    if (distance > this.maxDistance) { 
     // If distance is i.e 2.0 and maxDistance is 1.0 ==> adjust is 0.5 
     // which repositions x and y making distance 1.0 maintaining direction 
     double adjust = this.maxDistance/distance; 
     x = (float)(x * adjust); 
     y = (float)(y * adjust); 
    } 
    this.handleX = (int)x; 
    this.handleY = (int)y; 
} 

我可以根據需要更新答案,如果這不提供任何有用的結果。

+0

釘着它,歡呼隊友! –

+0

謝謝!這真是太棒了! –