Quick access to images and manipulation with Android

I am trying to port the emulator that I wrote in java for android. Everything went well, I was able to transfer most of my codes with slight changes, however, due to the way the emulation works, I need to display the image at the pixel level.

As for java desktop I use

int[] pixelsA = ((DataBufferInt) src.getRaster().getDataBuffer()).getData(); 

which allow me to get a link to the pixel buffer and update it on the fly (minimize object creation)

This is currently what my android emulator does for each frame

 @Override public void onDraw(Canvas canvas) { buffer = Bitmap.createBitmap(pixelsA, 256, 192, Bitmap.Config.RGB_565); canvas.drawBitmap(buffer, 0, 0, null); } 

pixelsA is an int [] array, pixelsA contains all the color information, so each frame will have to create a raster object by doing

 buffer = Bitmap.createBitmap(pixelsA, 256, 192, Bitmap.Config.RGB_565); 

which I find quite expensive and slow.

Is it possible to draw pixels efficiently with a canvas?

+8
android image pixel android-canvas draw
source share
4 answers

One pretty low level method, but works fine for me (with native code):

Create a Bitmap object the size of your visible screen. Also create a View object and implement the onDraw method.

Then, in your own code, you load your own libjnigraphics.so library, the search functions AndroidBitmap_lockPixels and AndroidBitmap_unlockPixels . These functions are defined in the Android source in bitmap.h.

Then you call lock / unlock on the bitmap, getting the address for the raw pixels. You should interpret the RGB pixel format as it really is (16-bit 565 or 32-bit 8888).

After changing the contents of the bitmap, you want to present it on the screen. Call View.invalidate() on the View . In onDraw , blit your bitmap to a given Canvas .

This method is very low and depends on the actual implementation of Android, however it is very fast, you can get 60fps without any problems.

bitmap.h is part of the Android NDK with version 8 platform, so this is the official way to do this with Android 2.2.

+10
source share

You can use the drawBitmap method, which avoids creating a bitmap every time, or even as a last resort, draw pixels one by one using drawPoint .

+4
source share

Do not recreate the bitmap every time. Try something like this:

 Bitmap buffer = null; @Override public void onDraw(Canvas canvas) { if(buffer == null) buffer = Bitmap.createBitmap(256, 192, Bitmap.Config.RGB_565); buffer.copyPixelsFromBuffer(pixelsA); canvas.drawBitmap(buffer, 0, 0, null); } 

EDIT: as indicated, you need to update the pixel buffer. And the bitmap must be mutable for this to happen.

0
source share

if pixelA is already an array of pixels (which I would make from your statement on holding colors), you can simply visualize them directly without converting:

 canvas.drawBitmap(pixelsA, 0, 256, 0, 0, 256, 192, false, null); 
0
source share

All Articles