我是使用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>
答案 0 :(得分:1)
答案不正确:&#34;这可能是因为它不是可绘制的位图。&#34;
正如小评论中所提到的,这是因为包含颜色的整数的大小。结果是消极或积极的。
所以:GetPixel正在返回正确的结果。
答案 1 :(得分:1)
可能有一种情况,当您将图像设置为适合XX scaletype时,您可能最终得到错误的值。移除scaletype并重试。
答案 2 :(得分:0)
这可能是因为它不是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());