0

I have an ImageView source with two colors. I want to touch a color and display a message. I have done the following but something is not going well because maybe I use the method getDrawingCache it has a delay on displaying the correct message..

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView img = (ImageView) findViewById(R.id.imageView);
    img.setOnTouchListener(this);

    ViewTreeObserver vto = img.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            finalHeight = img.getMeasuredHeight();
            finalWidth = img.getMeasuredWidth();

            r = (finalHeight*0.2973)*0.8109;
            centerx = finalWidth/2;
            centery = finalHeight;
            Log.e("hilength","Height: " + finalHeight + " Width: " + finalWidth);

            img.buildDrawingCache();
            bitmap = img.getDrawingCache();

            return true;
        }
    });

And my touch event

@Override
public boolean onTouch(View v, MotionEvent event)
{
    switch (v.getId())
    {
        case R.id.imageView:
            Log.d("Tag", "X,Y : " + event.getX() + "," + event.getY());

            int x = (int) event.getX();
            int y = (int) event.getY();
            int pixel = bitmap.getPixel(x,y);
            if(pixel == Color.parseColor("#94e3f9"))
            {
                Toast.makeText(MainActivity.this, "Blue Color", Toast.LENGTH_SHORT).show();
            }
            if(pixel == Color.parseColor("#f0c828"))
            {
                Toast.makeText(MainActivity.this, "Yellow Color", Toast.LENGTH_SHORT).show();
            }

            break;
    }

    return true;
}

In addition to the above , I am not sure if ViewTreeObserver is needed

Miaoulis Nikos
  • 182
  • 1
  • 15

1 Answers1

2

If it's an ImageView you could simply get the pixel value from the BitmapDrawable's Bitmap, though you may have to do a projection of event X/Y to the account for the ImageView's scaleType. If the Bitmap is not exactly the same size as the view then clicking at a certain position needs to be recalculated. The easiest projection for fitCenter would be something along the lines of:

float ratioX = event.getX() / view.getWidth(); // downscale to 0..1
int bitmapX = (int)(ratioX * bitmap.getWidth()); // upscale to size of bitmap

Also if it's just a matter of choosing two colors in the end you could just create two separate views with two separate onClick listeners for easy handling.

TWiStErRob
  • 44,762
  • 26
  • 170
  • 254