I am a newbie using Android and have been really working on this problem for four days now. I would really appreciate someone's help.
I have an image in an ImageView, and I would like to get the color of the part of the image that the user touches. For that I am using the Bitmap.getPixel() function. The problem is, that the returned value of this function,is always negative, which as the documentation says, is wrong. I am not getting the right color values, and I have really tried it in several ways (RGB, HSV...). Could somebody explain me please, why is my Bitmap.getPixel() function returning negative values all the time? Thanks in advance.
Here is my .java code:
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;
}
});
}
}
Here is my .xml code:
<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>
That's probably because it's not a BitmapDrawable
.
check here https://stackoverflow.com/a/16037415/906362 on my answer the proper way of getting a Drawable
into a Bitmap
.
edit:
try this:
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());