1

I am trying to get the color from an image where the user touches the image. I am able to get the x,y coordinates and can calculate the pixels from it using Matrix, however my issue is it is not giving me the right color.

private void getColor(MotionEvent event, Button capture) {
    float HeightRatio = (float) image.getHeight() / (float) imageView.getHeight();
    float WidthRatio = (float) image.getWidth() / (float) imageView.getWidth();
    Matrix inverse = new Matrix();
    imageView.getImageMatrix().invert(inverse);
    float[] touchPoint = new float[]{event.getX(), event.getY()};

    i2.setX(event.getX());
    i2.setY(event.getY());
    inverse.mapPoints(touchPoint);
    int x = Integer.valueOf((int) touchPoint[0]);
    int y = Integer.valueOf((int) touchPoint[1]);
    x = (int) (x * WidthRatio);
    y = (int) (y * HeightRatio);
    if (x < 0) {
        x = 0;
    } else if (x > image.getWidth() - 1) {
        x = image.getWidth() - 1;
    }

    if (y < 0) {
        y = 0;
    } else if (y > image.getHeight() - 1) {
        y = image.getHeight() - 1;
    }
    i2.setBackgroundColor(image.getPixel(x, y));
    i2.setVisibility(View.VISIBLE);
    capture.setBackgroundColor(image.getPixel(x, y));
}

This is the method i am using to get the color of the touched coordinate.

Thanks, Vipin

vipin jain
  • 11
  • 2

2 Answers2

0

try this:

final Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
imageView.setOnTouchListener(new OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
    int x = (int)event.getX();
    int y = (int)event.getY();
    int pixel = bitmap.getPixel(x,y);

    //then do what you want with the pixel data, e.g
    int redValue = Color.red(pixel);
    int blueValue = Color.blue(pixel);
    int greenValue = Color.green(pixel);        
    return false;
        }
   });
Aman Grover
  • 1,621
  • 1
  • 21
  • 41
0

Why so complicated? https://stackoverflow.com/a/7807442/1979882

Have you tried this?:

private void getColor(MotionEvent event, Button capture) {
float[] touchPoint = new float[]{event.getX(), event.getY()};
float x = touchPoint[0];
float y = touchPoint[1];
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);

capture.setBackgroundColor(image.getPixel(x, y));
}
Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
  • Hi, Thanks for your response, i have tried above code however still do not get the right color at the touch point. – vipin jain Sep 01 '16 at 14:32