0

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.

Den
  • 3
  • 2
  • If you're happy with CaseyB's answer, you should mark it as 'accepted' by clicking the tickmark to its left. That gives him 'reputation points' and tells everyone else that the problem has been solved. – Steve Haley Mar 04 '10 at 10:24
  • For alternative approach see this http://stackoverflow.com/questions/11560882/call-to-getdrawingcache-fails-on-api-8-everytime – Ron Jul 20 '12 at 15:30

2 Answers2

1

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
  • 24,780
  • 14
  • 77
  • 112
  • 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 Mar 03 '10 at 23:05
  • 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 Mar 03 '10 at 23:23
  • Yep, your suggestion is ok. See my comments in my own answer to this. Thank you!. – Den Mar 03 '10 at 23:26
0

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
  • 3
  • 2