user1703737
user1703737

Reputation: 533

How to get pixel color in Android?

I have set a PNG image(image having transparent background) as button background, When I touch the button it shows me X-coordinate and Y-coordinate of the button’s touched position but, I want to know pixel color of the touched position of the button.

Actually I want to know whether the touched position is transparent area of the button or colored area of the button. You can check my code that I have developed for this purpose. Please help me in this respect; your help would be cordially appreciated.

 button.setOnTouchListener(new OnTouchListener() 
        {
            public boolean onTouch(View v, MotionEvent event) 
            {

                int x_coordinate  = (int)event.getX(); 
                int y_coordinate = (int)event.getY(); 

            //int color = Bitmap.getPixel(x,y);

            if (event.getAction() == MotionEvent.ACTION_DOWN) 
                {
                }

            if (event.getAction() == MotionEvent.ACTION_UP) 
                {
                }

                return true;
            }
        });

Upvotes: 1

Views: 9585

Answers (3)

MalaKa
MalaKa

Reputation: 3794

First, you can get the Bitmap with the BitmapFactory like this:
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic1);

Now you have the Bitmap. On this Bitmap, you can call the function getPixel(int x, int y) to get the Color of this Pixel.
I guess you then can get the alpha from that Color..

See the following links for further information:

Upvotes: 2

Abx
Abx

Reputation: 2882

Try this

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
    int color=bitmap.getPixel(x_coordinate, y_coordinate);

Use this color in your if statements to do the required operations

Upvotes: 2

Egor
Egor

Reputation: 40203

Try this

Drawable drawable = button.getBackground();
Bitmap bmp = ((BitmapDrawable) drawable).getBitmap();
int color = bmp.getPixel(x_coordinate, y_coordinate);

Upvotes: 3

Related Questions