Wednesday 28 April 2010

Android Render To Bitmap

Here is a little bit of source code for android that show you how to render some graphics to an integer array and pass that into an ImageView class. The bit I do not like very much is the checking for the size change and reallocating the array.

At the point on onResume the display ImageView has not been resized to it correct size so when you call getWidth/getHeight it returns zero. The only way I could see to handle this was to dynamically update it. The initial size of 50 is needed as the ImageView object is only resized then it actually has some data in it. Well as far as I can see anyway. If there is a better way to do this please let me know.

Incidentally if you choose to turn off (comment out) the display you get quite a nice effect and android attempt to stretch and smooth the image.

public class RenderToImage extends Activity {
int width = 50, height = 50;
int pixels[] = new int[width * height]; // Render into this
ImageView display;
Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

private Runnable runnable = new Runnable() {

public void run() {
updateDisplay();
display.invalidate();
handler.postDelayed(runnable, 10);
}
};

@Override
protected void onResume() {
super.onResume();
display = (ImageView) findViewById(R.id.RenderImage);
handler = new Handler();

handler.postAtTime(runnable, 100);
}

void createMess() {
Log.d("WIDTH", "" + display.getWidth()+ " height:" + display.getHeight());

for (int i = 0; i < pixels.length; ++i) {
pixels[i] = 0xffaa88aa;
}

for (int i = 0; i < 1000; ++i) {
pixels[(int) Math.floor(Math.random() * (pixels.length-1)) ] = 0xff00ff00;
}
}

void updateDisplay() {
if (width != display.getWidth() && display.getWidth() != 0) {
width = display.getWidth();
height = display.getHeight();
pixels = new int[width * height];
}

createMess();
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.setPixels(pixels, 0, width, 0, 0, width, height);
display.setImageBitmap(bm);
display.invalidate();
}
}

No comments:

Post a Comment