views:

309

answers:

2

Hello everyone. In my app I need to draw a widget contents onto Bitmap.

The code(pseudo) is as follows:

AppWidgetHostView widget;
Bitmap bitmap;
...
widget = pickWidget();
...

bitmap = Bitmap.createBitmap(128, 128, Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas(bitmap);
widget.draw(canvas);

I'm sure that pickWidget() works ok - if do setContentView(widget); I get the widget displayed properly on full screen. Bitmap I'm drawing to also displays ok - if I draw on a canvas using drawCircle or do setPixel() on the Bitmap for example I can see the drawings. So the issue is with widget.draw(), it doesn't seem to have any effect on the bitmap. Please share your thoughts.

+1  A: 

An easier way to do this is with the View's DrawingCache. Like this:

widget.buildDrawingCache(true);
Bitmap bitmap = widget.getDrawingCache(true);
widget.destroyDrawingCache();

This will give you a bitmap with the view already drawn into it. The boolean values that get passed in are whether to scale the bitmap or not. You may need to change those values based on your needs.

CaseyB
Thanks for the reply.But in my case getDrawingCache returns null so the end result is the same.How else can I check that I have a valid widget?
Den
Are you calling `widget.buildDrawingCache(true)` first? According to the documentation the only time that `getDrawingCache()` should return null is when caching is not enabled.
CaseyB
Yep, your suggestion is ok.See my comments in my own answer to this. Thank you!.
Den
A: 

I should've given myself couple more minutes :) Problem solved. Actually both methods worked - I just had to explicitly call widget.measure followed by widget.layout to set widget's sizes (something that is, I assume, automatically done when you do setContentView()). My app is performance-sensitive so it's good to have more than one method to choose from. Thank you!

Den