2017-07-10 46 views

回答

0

AFAIK由android設計的所有視圖都是矩形的。您可以擴展視圖類,在onSizeChanged(使用實體部分和數學的邊界以及視圖的寬度和高度)中爲圖像定義閉合路徑,並覆蓋其onTouch以僅響應落在上面定義的閉合路徑中的觸摸。所以最終你將能夠實現你想要的行爲。

0

儘管Virendra Singh的回答是正確的,但我覺得在一般情況下使用路徑可能太困難了。

要處理所有情況,您需要每像素測試。每像素測試繪製視圖並測試觸摸像素是否可點擊。代碼非常短:

public class BitmapButton extends Button { 

    private final Bitmap bitmap; 
    private final Canvas canvas; 

    public BitmapButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); 
     canvas = new Canvas(bitmap); 
    } 

    public boolean onTouchEvent(MotionEvent event) { 
     bitmap.setPixel(0, 0, 0); // reset pixel 
     canvas.save(); 
     canvas.translate(-event.getX(), -event.getY()); 
     draw(canvas); // draw only the touched pixel 
     canvas.restore(); 
     // pass touch events when the pixel is clickable 
     return Color.alpha(bitmap.getPixel(0, 0)) > 0 && super.onTouchEvent(event); 
    } 
} 
相關問題