Get Pixel Values from Android Canvas

I'm currently writing an Android game using surfaceView. I've optimized the game as much as possible and it runs quite smoothly. However, I have collision detection incorporated which is a bit messy. I would like to do collision detection by reading pixels directly from the canvas. Is this possible to do? The closest to this that I have found was to attach a new bitmap to the canvas using setBitmap. Then when I drew to the canvas, the bitmap would be updated. Would this be the way to go? Thanks.

Answers


Although you should manage the collision detection in a different way, you can get the pixel color on a given position with the next line of code:

mView.mBitmap.getPixel(j, i)

mView is the View that contains your canvas and mBitmap is the Bitmap with which you created your canvas:

Canvas mCanvas = new Canvas(mBitmap);

From the Canvas API:

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).

So you wouldn't ever ask a canvas for pixel data, because the canvas itself doesn't really "own" pixel data. The canvas which you use to make draw calls is always attached to a bitmap (the one you're drawing on), so that bitmap is where you should get your pixel data from.

Collision detection is usually costly, but going to a bitmap-based process could make it even worse, depending on what you're trying to do. Just a heads up.


I agree with Josh. If precision is that important in your app, you may want to incorporate screen size/resolution data into some kind of physics engine. Trying to build a physics engine based entirely on visual processing is probably unnecessarily costly.


Need Your Help

Python equivalent of PyErr_Print()

python c cpython sys traceback

What is the Python API equivalent of PyErr_Print(), from the C interface?

wordpress plugin MVC page structure

wordpress model-view-controller wordpress-plugin

I'm working on a wordpress plugin that takes the whole page and is about planing a trip.