2013-08-22 16 views
0

嗨我想在我觸摸圖像視圖時獲取像素顏色,當xml中圖像視圖的寬度和高度包裝時,此代碼工作正常內容當圖像視圖的寬度設置時獲取像素顏色當圖像視圖包含小圖像時match_parent

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight=".2" 
     android:orientation="vertical" 
     android:gravity="center"> 

     <ImageView 
      android:id="@+id/iv_cam" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/ic_launcher" > 
     </ImageView> 
    </LinearLayout> 

,在XML文件中當我設置寬度和圖像視圖渦卷內容的高度通過執行此小圖像成爲拉伸 錯誤出現 E/MessageQueue-到

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight=".2" 
     android:orientation="vertical" 
     android:gravity="center"> 

     <ImageView 
      android:id="@+id/iv_cam" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:src="@drawable/ic_launcher" > 
     </ImageView> 
    </LinearLayout> 

匹配父問題出現JNI(1006):j ava.lang.IllegalArgumentException:x必須< bitmap.width()

我怎麼能解決這個...

@覆蓋 公共布爾onTouch(視圖V,MotionEvent事件){

if(event.getAction() == MotionEvent.ACTION_DOWN){   

    ImageView iv = ((ImageView)v);  
    Bitmap bmp = ((BitmapDrawable)iv.getDrawable()).getBitmap(); 

    int pixel = bmp.getPixel((int)event.getX(),(int)event.getY());// error comes in this line 
    int alphaValue = Color.alpha(pixel); 
    int redValue = Color.red(pixel); 
    int blueValue = Color.blue(pixel); 
    int greenValue = Color.green(pixel); 

    Toast.makeText(this,"[" +alphaValue+"," +redValue+","+greenValue+","+blueValue+"]", Toast.LENGTH_LONG).show(); 

    } 

    return false; 
} 

回答

0

您需要根據位圖本身檢查位圖的尺寸。

if ((bmp.getHeight() < (int)event.getY() || (bmp.getWidth() < (int)event.getX()) { 
// not within range 
} 
+0

不,這不是正是我想要的,我可以處理WRAP_CONTENT錯誤是什麼,但我想的ImageView以適應屏幕,我認爲bmp.getHeight()將返回原來的高度,而不是拉伸後,所以你有任何其他建議....並順便謝謝你的回覆 –

+0

你有沒有嘗試iv.setScaleType(ScaleType.FIT_XY)或任何其他尺度? – jaesanx

0

我知道這是一個老問題,但它可能仍然相關。據我所知,位圖引用的像素不同於通過事件getPixel()獲得的像素。我所做的是抵消這些像素如下:

Bitmap bmp = Bitmap.createBitmap(img.getDrawingCache()); 
    Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    int width = size.x; 
    int height = size.y;   
    int [] imgCenter = new int[2]; 
    img.getLocationOnScreen(imgCenter); 
    int x = evX - imgCenter[0]; // These are your desired coordinates 
    int y = evY - imgCenter[1]; // evX & evY are the event's coordinates 
相關問題