我是一个使用 Android 的新手,现在已经花了四天时间来解决这个问题。我真的很感谢有人的帮助。
我在 ImageView 中有一个图像,我想获取用户触摸的图像部分的颜色。为此,我使用 Bitmap.getPixel() 函数。问题是,这个函数的返回值总是负数,正如文档所说,这是错误的。我没有获得正确的颜色值,并且我确实以多种方式尝试过(RGB、HSV...)。有人可以解释一下为什么我的 Bitmap.getPixel() 函数总是返回负值吗?提前致谢。
这是我的 .java 代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setOnTouchListener(new ImageView.OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Drawable imgDrawable = ((ImageView)imageView).getDrawable();
Bitmap mutableBitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mutableBitmap);
imgDrawable.draw(canvas);
int pixel = mutableBitmap.getPixel((int)event.getX(), (int)event.getY());
Log.i("PIXEL COLOR", ""+pixel);
int alpha = Color.alpha(pixel);
int red = Color.red(pixel);
int blue = Color.blue(pixel);
int green = Color.green(pixel);
String color = String.format("#%02X%02X%02X%02X", alpha, red, green, blue);
Log.i("RGB", color);
float[] hsv = new float[3];
Color.RGBToHSV(red, green, blue, hsv);
Log.i("HSV_H", "Hue=" + hsv[0]);
Log.i("HSV_H", "Saturation=" + hsv[1]);
Log.i("HSV_H", "Value=" + hsv[2]);
}
return true;
}
});
}
}
这是我的 .xml 代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="@drawable/lapices" />
</LinearLayout>
最佳答案
这可能是因为它不是 BitmapDrawable
。
查看此处https://stackoverflow.com/a/16037415/906362根据我的回答,将 Drawable
转换为 Bitmap
的正确方法。
编辑:
试试这个:
Drawable imgDrawable = ((ImageView)imageView).getDrawable();
Bitmap mutableBitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mutableBitmap);
imgDrawable.draw(canvas);
int pixel = mutableBitmap.getPixel((int)event.getX(), (int)event.getY());
关于Android Bitmap.getPixel 总是返回负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038369/