2012-01-29 212 views
7

我已經創建/試圖創建,通過使用ImageButton「小部件」android的圓形按鈕。 但由於該類型的按鈕被視爲一個正方形,我的PNG圖像也被視爲一個具有透明背景的正方形,那麼如何避免用戶可以按下圓形按鈕之外的按鈕?現在..他們可以按下按鈕的「角落」,並仍然會觸發點擊事件。 是否有任何可以在Photoshop中完成的特殊映射圖層或以任何方式更改圖像按鈕的半徑所以它符合我的形象「圓潤」..或任何想法?Android中的圓形按鈕..避免按下「外部」按鈕?

提前感謝!..和英文不好抱歉..

回答

5

嘗試勾股定理和onTouch,簡單易用的方式來做到這一點。

public boolean inCircle(MotionEvent e, int radius, int x, int y) { 
    int dx = e.x - x; 
    int dy = e.y - y; 
    double d = Math.sqrt((dx * dx) + (dy * dy)); 
    if(d < radius) 
     return true; 
    return false; 
} 

x,y是圓的位置,半徑是半徑,e是TouchEvent。

@Override 
public boolean onTouch(View arg0, MotionEvent arg1) { 
    if(arg1.getAction() == MotionEvent.ACTION_DOWN){ 
      if(inCircle(arg1, radius, xCircle, yCircle){ 
        //do whatever you wanna do here 
        } 
      } 
    return false; 
} 
+0

是使用dp或像素的單位?..按位置..是使用圓的中間位置的位置..還是左上角? – Inx 2012-01-29 02:03:41

+0

感謝您的幫助:) – Inx 2012-01-29 02:04:10

+0

試過這個。但它看起來像從左上角開始計數,並且不會移動從中算起的圓的「樞軸」。 – Inx 2012-01-29 02:55:40

2

我正在使用ImageView作爲我的圓形按鈕,並且我需要對@ Daniel的代碼進行一些更改以使其按照我想要的方式工作。這裏是我的代碼:

private boolean mStillDown = false; 

public boolean inCircle(MotionEvent e, float radius, float x, float y) { 
    float dx = e.getX() - x; 
    float dy = e.getY() - y; 
    double d = Math.sqrt((dx * dx) + (dy * dy)); 
    if(d < radius) 
     return true; 
    return false; 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 

    int action = event.getAction(); 
    boolean inCircle = inCircle(event, getWidth()/2.0f, getWidth()/2.0f, getHeight()/2.0f); 

    if(inCircle){ 
     if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN){ 
      this.setPressed(true); 
      mStillDown = true; 
     }else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP){ 
      if(this.isPressed()){ 
       this.performClick(); 
       this.setPressed(false); 
       mStillDown = false; 
      } 
     }else if(action == MotionEvent.ACTION_MOVE && mStillDown){ 
      this.setPressed(true); 
     } 
    }else{ 
     if(action == MotionEvent.ACTION_MOVE){ 
      this.setPressed(false); 
     }else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_OUTSIDE){ 
      mStillDown = false; 
     } 
    } 

    return true; 
} 

希望這對某人有用。