1

I am trying to use the drawing cache to make a bitmap of a programatically created view, like so:

LinearLayout view = new LinearLayout(context);
view.setBackground(context.getResources().getColor(R.color.green));
view.setDrawingCacheEnabled(true);

int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY);
int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
view.measure(w, h);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());

I expect it to output an 800x600 green bitmap; instead I get an 800x600 white bitmap. What am I doing wrong?

plátano plomo
  • 1,672
  • 1
  • 18
  • 26
  • 1
    "I expect it to output an 800x600 green bitmap" -- why? A `LinearLayout` is not magically green, and you have no code in here to make it be green. Beyond that, you are not drawing it anywhere. Get rid of all the drawing cache stuff, create a `Bitmap`-backed `Canvas`, and `draw()` the view to that `Canvas`. The `Bitmap` will contain the results of the drawing. – CommonsWare Jan 09 '17 at 23:11

1 Answers1

0

Thanks to @CommonsWare, this works:

    LinearLayout view = new LinearLayout(context);
    view.setBackgroundColor(context.getResources().getColor(R.color.green));
    int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY);
    int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
    view.measure(width, height);

    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    view.draw(canvas);
blackgreen
  • 34,072
  • 23
  • 111
  • 129
plátano plomo
  • 1,672
  • 1
  • 18
  • 26