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

一世执手 提交于 2019-11-26 11:23:27

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/6272859/getting-the-pixel-color-value-of-a-point-on-an-android-view-that-includes-a-bitm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!