I am trying to get the color of the spot where I touched on an ImageView. And I succeeded using getPixel(x,y) for getting the color, but on another spot I am not getting the color of the pixel where I touched; I am getting the color of a different pixel.
ImageView xml:
<ImageView
android:id="@+id/ImgSelected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/todo" />
Assigning Bitmap to ImageView:
imageViewSelected.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageViewSelected.setImageBitmap(bm2);
OnTouch() for getting the pixel
@Override
public boolean onTouchEvent(MotionEvent event) {
if (imageViewSelected.getVisibility() == 0) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] { eventX, eventY };
Matrix invertMatrix = new Matrix();
imageViewSelected.getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int) eventXY[0]);
int y = Integer.valueOf((int) eventXY[1]);
Drawable imgDrawable = imageViewSelected.getDrawable();
Bitmap bitmap = ((BitmapDrawable) imgDrawable).getBitmap();
// Limit x, y range within bitmap
if (x < 0) {
x = 0;
} else if (x > bitmap.getWidth() - 1) {
x = bitmap.getWidth() - 1;
}
if (y < 0) {
y = 0;
} else if (y > bitmap.getHeight() - 1) {
y = bitmap.getHeight() - 1;
}
int touchedRGB = bitmap.getPixel(x, y);
ImgColorPublic.touchX = (int) event.getX();
ImgColorPublic.touchY = (int) event.getY();
ImgColorPublic.touchColor = Integer.toHexString(touchedRGB);
}
return false;
}
Using this code, for some images I am getting the correct value, but not for all images.