[Android View] 判斷是否點中一個動態可旋轉、可縮放、可移動的圖片

轉自:http://blog.csdn.net/Dylan465/article/details/8351007

 

先看圖,效果就是這樣了,點中圖片會變藍色



項目下載地址:

http://download.csdn.net/download/dylan465/4911020

如果一個圖片只是簡單的移動,這個很容易就可以判斷出觸控點是否落在繪製bitmap的矩形區域,但這個bitmap能動態旋轉、縮放那就不能用老一套的方法了。

圖片左上角的點在圖片旋轉之後A的座標落在哪裏?圖片縮放後A又在哪裏?座標的轉換涉及到比較複雜的計算公式,好在有Matrix!矩陣是個好東西!哈哈!請看代碼

監聽onTouch並轉換座標

  1. @Override  
  2. public boolean onTouchEvent(MotionEvent event) {  
  3.     // TODO Auto-generated method stub  
  4.     if (event.getAction() == MotionEvent.ACTION_DOWN) {  
  5.   
  6.         // 獲取觸控點  
  7.         float tx = event.getX();  
  8.         float ty = event.getY();  
  9.         // 存放新座標的數組  
  10.         float[] dst = new float[2];  
  11.         // 觸控點座標的數組  
  12.         float[] src = { tx, ty };  
  13.         Matrix matrix = new Matrix();  
  14.         // 獲取繪製圖片的Matrix,並轉換mantrix  
  15.         // set inverse to be the inverse of this matrix.  
  16.         if (object.getMatrix().invert(matrix)) {  
  17.             // 觸控座標根據matrix轉換成新的座標,並存放於dst  
  18.             matrix.mapPoints(dst, src);  
  19.         }  
  20.         // 判斷是否擊中  
  21.         if (object.isHitObject(dst[0], dst[1])) {  
  22.             object.setBitmap(hitBitmap);  
  23.         } else {  
  24.             object.setBitmap(missBitmap);  
  25.         }  
  26.     } else if (event.getAction() == MotionEvent.ACTION_UP) {  
  27.         object.setBitmap(missBitmap);  
  28.     }  
  29.     return true;  
  30. }  
	@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

  1. /** 
  2.  * 判斷是否擊中bitmap 
  3.  */  
  4. public boolean isHitObject(float hitX, float hitY) {  
  5.     if (hitX >= 0 && hitX <= getBitmap().getWidth() && hitY >= 0  
  6.             && hitY <= getBitmap().getHeight()) {  
  7.         return true;  
  8.     }  
  9.     return false;  
  10. }  
發佈了19 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章