我创建了一个代表汽车的图像,我用不同的颜色为汽车的每个组件着色,例如引擎盖的 RGB 颜色为 251,252,252。
此图像通过 TileView 显示在屏幕上,我需要实现一个函数来获取我触摸的像素的颜色,我发布的函数有效,但返回给我的是与原始颜色不同的 RGB 颜色一个。
这里我展示一下区别:
- 原始图片:251,252,252
- 位图图像:255,255,255
我不明白为什么在创建位图(用于获取像素的颜色)时颜色会发生变化,或者问题出在 getDrawingCache() 函数中可能会改变一些颜色值,我真的不知道不知道...
这是我的代码的一部分:
tileView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int eventAction = motionEvent.getAction();
switch (eventAction) {
case MotionEvent.ACTION_DOWN:
double x = tileView.getCoordinateTranslater().translateAndScaleAbsoluteToRelativeX(tileView.getScrollX() + motionEvent.getX(), tileView.getScale());
double y = tileView.getCoordinateTranslater().translateAndScaleAbsoluteToRelativeY(tileView.getScrollY() + motionEvent.getY(), tileView.getScale());
try {
tileView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(tileView.getDrawingCache());
File file = new File(Environment.getExternalStorageDirectory() + "/bitmap.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
int touchColor;
if (bitmap == null) {
touchColor = 0;
} else {
touchColor = bitmap.getPixel((int) motionEvent.getX(), (int) motionEvent.getY());
}
int redValue = Color.red(touchColor);
int blueValue = Color.blue(touchColor);
int greenValue = Color.green(touchColor);
Log.wtf("DEBUG", "-Red: " + redValue + " -Green: " + greenValue + " -Blue: " + blueValue);
tileView.setDrawingCacheEnabled(false);
tileView.destroyDrawingCache();
bitmap.recycle();
} catch (Exception e) {
}
addPin(tileView, x, y);
break;
}
return false;
}
});
最佳答案
这可能是与图像有关的问题,而不是与代码有关的问题。我建议您创建一个 png 格式的图像并为其着色,然后将背景设置为该图像。
过去我碰巧因为一些奇怪的原因,颜色不完全“适合”。
关于java - getPixel() 函数中的问题,错误的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719766/