Home Ask Login Register

Developers Planet

Your answer is one click away!

Aaron Miller February 2016

Adding an on touch coordinate and pixel color display

My current code allows you to take an image and display it inside an image view. How would I implement the ability to touch anywhere on the image and display the color at that pixel, the color would then fill a solid object such as a rectangle to display what it is. I'm hoping the solution contains RGB values as i need them for my application later on.

import android.app.Activity;
    import android.content.Intent;
    import android.graphics.drawable.Drawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;

    import java.io.File;

    public class MainActivity extends Activity {

        private static final int CONTENT_REQUEST = 1337;
        private File output = null;
        Button button;
        ImageView imageView;

        public void onCreate(Bundle savedInstanceState) {
            button = (Button) findViewById(R.id.CameraButton);
            imageView = (ImageView) findViewById(R.id.Image_view);
            button.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {

                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

                    output = new File(dir, "COMP4Image.jpeg");
                    i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));

                    startActivityForResult(i, CONTENT_REQUEST);



        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRE        


pdegand59 February 2016

I won't provide code but the solution is fairly easy to implement.

Add a View.OnTouchListener to your ImageView.

This listener will respond to every single touch event happening on the View. (touch down, move, touch up etc...)

You can retrieve the coordinate of the event with MotionEvent.getX(int) (and y equivalent). (read MotionEvent documentation to learn more about pointers).

When you have X and Y coordinates of the touch event, you can get the pixel color of the pointed pixel in the bitmap with Bitmap.getPixel(int, int) (see here to get the Bitmap attached to your ImageView).

Voila, you have the selected color. Just print it into a rectangular view below your image view and use Color utility class to extract ARVB components of the selected color.

Hope this helps.

Post Status

Asked in February 2016
Viewed 2,392 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life