設置觸摸面板的監聽;java
root.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: System.out.println("action down"); break; case MotionEvent.ACTION_MOVE: System.out.println("action move"); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout. LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT); lp.leftMargin = (int) event.getX(); lp.topMargin = (int) event.getY(); root.setLayoutParams(lp); //獲取觸摸點的座標 System.out.println(String.format("x:%f,y:%f",event.getX(),event.getY())); break; case MotionEvent.ACTION_UP: System.out.println("action up"); break; } return true; //觸發成功纔會進行後續事件的觸發 } });
2.若是想獲取多個觸摸點可採用方法:ide
event.getPointerCount();
3.獲取某個觸摸點的座標:code
event.getX(*); event.getY(*);
4.安卓圖片的放大縮小縮放orm
root = (FrameLayout)findViewById(R.id.container); imageView = (ImageView) findViewById(R.id.img); root.setOnTouchListener(new View.OnTouchListener() { float currentDistance; //當前的位置 float lastDistance = -1; //上次的位置 @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: System.out.println("action move"); System.out.println(event.getPointerCount()); //只有當觸摸點超過兩個求距離 if(event.getPointerCount() >= 2) { float offsetX = event.getX(0)-event.getX(1); //獲取一條邊 float offsetY = event.getY(0)-event.getY(1); //獲取另外一條邊 //根據勾股定理獲取觸摸兩點之間的距離 currentDistance = (float) Math.sqrt(offsetX*offsetX +offsetY*offsetY); //對上次的觸摸距離進行初始化 if(lastDistance < 0) { lastDistance = currentDistance; } else { //在安卓環境中,當手指放上去的時候就會有顯示,會有偏差,若是按照理論 //設置爲零,當你的手指剛放上去就會忽大忽小,因此這塊的5是一個容錯範圍, //可根據本身的軟件的具體環境設置相應的值 if(currentDistance -lastDistance > 5 ) { System.out.println("放大"); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) imageView.getLayoutParams(); lp.width = (int) (1.1f*imageView.getWidth()); lp.height = (int) (1.1f*imageView.getHeight()); imageView.setLayoutParams(lp); lastDistance = currentDistance; } else if(lastDistance -currentDistance > 5) { System.out.println("縮小"); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) imageView.getLayoutParams(); lp.width = (int) (0.9f*imageView.getWidth()); lp.height = (int) (0.9f*imageView.getHeight()); imageView.setLayoutParams(lp); lastDistance = currentDistance; } } } break; case MotionEvent.ACTION_UP: break; } return true; //觸發成功纔會進行後續事件的觸發 } });
若是一直縮小到0,那麼這張圖片就會消失,因此,應該增長一個爲零判斷,這部分可自行設置。
事件