轉自:http://blog.csdn.net/Dylan465/article/details/8351007
先看圖,效果就是這樣了,點中圖片會變藍色
項目下載地址:
http://download.csdn.net/download/dylan465/4911020
如果一個圖片只是簡單的移動,這個很容易就可以判斷出觸控點是否落在繪製bitmap的矩形區域,但這個bitmap能動態旋轉、縮放那就不能用老一套的方法了。
圖片左上角的點在圖片旋轉之後A的座標落在哪裏?圖片縮放後A又在哪裏?座標的轉換涉及到比較複雜的計算公式,好在有Matrix!矩陣是個好東西!哈哈!請看代碼
監聽onTouch並轉換座標
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- // TODO Auto-generated method stub
- if (event.getAction() == MotionEvent.ACTION_DOWN) {
- // 獲取觸控點
- float tx = event.getX();
- float ty = event.getY();
- // 存放新座標的數組
- float[] dst = new float[2];
- // 觸控點座標的數組
- float[] src = { tx, ty };
- Matrix matrix = new Matrix();
- // 獲取繪製圖片的Matrix,並轉換mantrix
- // set inverse to be the inverse of this matrix.
- if (object.getMatrix().invert(matrix)) {
- // 觸控座標根據matrix轉換成新的座標,並存放於dst
- matrix.mapPoints(dst, src);
- }
- // 判斷是否擊中
- if (object.isHitObject(dst[0], dst[1])) {
- object.setBitmap(hitBitmap);
- } else {
- object.setBitmap(missBitmap);
- }
- } else if (event.getAction() == MotionEvent.ACTION_UP) {
- object.setBitmap(missBitmap);
- }
- return true;
- }
@Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_DOWN) { // 獲取觸控點 float tx = event.getX(); float ty = event.getY(); // 存放新座標的數組 float[] dst = new float[2]; // 觸控點座標的數組 float[] src = { tx, ty }; Matrix matrix = new Matrix(); // 獲取繪製圖片的Matrix,並轉換mantrix // set inverse to be the inverse of this matrix. if (object.getMatrix().invert(matrix)) { // 觸控座標根據matrix轉換成新的座標,並存放於dst matrix.mapPoints(dst, src); } // 判斷是否擊中 if (object.isHitObject(dst[0], dst[1])) { object.setBitmap(hitBitmap); } else { object.setBitmap(missBitmap); } } else if (event.getAction() == MotionEvent.ACTION_UP) { object.setBitmap(missBitmap); } return true; }
判斷是否擊中bitmap
- /**
- * 判斷是否擊中bitmap
- */
- public boolean isHitObject(float hitX, float hitY) {
- if (hitX >= 0 && hitX <= getBitmap().getWidth() && hitY >= 0
- && hitY <= getBitmap().getHeight()) {
- return true;
- }
- return false;
- }