我正在尝试获取我在ImageView上触摸的地点的颜色。我成功地使用getPixel(x,y)获取颜色,但在另一个地方我没有得到我触摸的像素的颜色;我得到了不同像素的颜色。
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" />
将位图分配给ImageView:
imageViewSelected.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageViewSelected.setImageBitmap(bm2);
用于获取像素的OnTouch()
@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;
}
使用此代码,对于某些图像,我得到正确的值,但不是所有图像。