Search code examples
androidimageviewtouch-eventontouchlistenerontouch

ImageView - get color of touched pixel


I have following image, consisting of three colors (white, grey, black):

enter image description here

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

On touch, I want to find out, which of these areas has been clicked - white, grey or black. I tried 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;
    });
}

However, each time, following exception occurs:

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

As stated almost everywhere, this is the solution for my type of problem. However, it is not working in my project. Could somebody help me with this one?


Solution

  • It is not working because the size of the bitmap is different from the size of the ImageView

    Try this,

    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;
    });