0

嗨,我想在触摸图像视图时获得像素颜色,当 xml 中图像视图的宽度和高度是包装内容时,此代码工作正常

    <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 文件中设置图像视图包装内容的宽度和高度以匹配父级时,会出现问题

    <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>

通过这样做,小图像变得拉伸错误来 E/MessageQueue-JNI(1006): java.lang.IllegalArgumentException: x must be < bitmap.width()

我该如何解决这个...

@Override public boolean onTouch(View 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;
}
4

2 回答 2

0

您需要对照位图本身检查位图的尺寸。

if ((bmp.getHeight() < (int)event.getY() || (bmp.getWidth() < (int)event.getX() ) {
// not within range
}
于 2013-08-22T19:07:15.587 回答
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 
于 2015-05-23T12:11:18.620 回答