ImageView - 获取触摸像素的颜色

ImageView - get color of touched pixel

我有以下图片,由三种颜色(白色、灰色、黑色)组成:

 <ImageView
        android:id="@+id/iv_colors"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:scaleType="fitStart"
        android:adjustViewBounds="true"
        android:src="@drawable/colors"
        />

触摸时,我想知道点击了这些区域中的哪一个 - 白色、灰色或黑色。我试过 this approach:

final Bitmap bitmap = ((BitmapDrawable) ivColors.getDrawable()).getBitmap();
ivColors.setOnTouchListener((v, event) -> {
        int x = (int) event.getX();
        int y = (int) event.getY();
        int pixel = bitmap.getPixel(x,y);
        int redValue = Color.red(pixel);
        int blueValue = Color.blue(pixel);
        int greenValue = Color.green(pixel); 
        return false;
    });
}

但是,每次都会发生以下异常:

java.lang.IllegalArgumentException: x must be < bitmap.width()

正如几乎所有地方所说的,这是我的问题类型的解决方案。但是,它在我的项目中不起作用。有人可以帮我解决这个问题吗?

它不起作用,因为位图的大小与 ImageView 的大小不同

试试这个,

imageView.setOnTouchListener((v, event) -> {

    int viewX = (int) event.getX();
    int viewY = (int) event.getY();

    int viewWidth = imageView.getWidth();
    int viewHeight = imageView.getHeight();

    Bitmap image = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    int imageX = (int)((float)viewX * ((float)imageWidth / (float)viewWidth));
    int imageY = (int)((float)viewY * ((float)imageHeight / (float)viewHeight));

    int currPixel = image.getPixel(imageX, imageY);

    Log.d("Coordinates", "(" + String.valueOf(Color.red(currPixel)) + ", " + String.valueOf(Color.blue(currPixel)) + ", " + String.valueOf(Color.green(currPixel)) + ") Pixel is: " + currPixel);

    return false;
});