Getting the pixel color value of a point on an Android View that includes a Bitmap-backed Canvas

Ellen Spertus picture Ellen Spertus · Jun 8, 2011 · Viewed 16.4k times · Source

I'm trying to figure out the best way to get the pixel color value at a given point on a View. There are three ways that I write to the View:

  1. I set a background image with View.setBackgroundDrawable(...).

  2. I write text, draw lines, etc., with Canvas.drawText(...), Canvas.drawLine(...), etc., to a Bitmap-backed Canvas.

  3. I draw child objects (sprites) by having them write to the Canvas passed to the View's onDraw(Canvas canvas) method.

Here is the onDraw() method from my class that extends View:

   @Override
   public void onDraw(Canvas canvas) {
      // 1. Redraw the background image.
      super.onDraw(canvas);
      // 2. Redraw any text, lines, etc.
      canvas.drawBitmap(bitmap, 0, 0, null);
      // 3. Redraw the sprites.
      for (Sprite sprite : sprites) {
        sprite.onDraw(canvas);
      }
    }

What would be the best way to get a pixel's color value that would take into account all of those sources?

Answer

jkhouw1 picture jkhouw1 · Jun 8, 2011

How about load the view to a bitmap (at some point after all your drawing/sprites etc is done), then get the pixel color from the bitmap?

public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
    v.draw(c);
    return b;
}

then use getPixel(x,y) on the result?

http://developer.android.com/reference/android/graphics/Bitmap.html#getPixel%28int,%20int%29