Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...