从触摸事件的图像视图中选择颜色

时间:2016-08-31 13:04:02

标签: android

我试图从用户触摸图像的图像中获取颜色。我能够获得x,y坐标,并且可以使用Matrix计算它的像素,但是我的问题是它没有给我正确的颜色。

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

这是我用来获取触摸坐标颜色的方法。

谢谢, VIPIN

2 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

为什么这么复杂? https://stackoverflow.com/a/7807442/1979882

你试过这个吗?:

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