3

Is there a way to generate a drawable object from a layout?

In fact, I need a cropped part of my initial layout, and my idea is to transform the layout into a drawable object and then to crop drawable.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Gratzi
  • 4,633
  • 12
  • 42
  • 58
  • OK, but what will be with the controls behaviour on that drawable? Even if that is pure text, I am afraid it will look ugly. IMO, if you want to reuse that layout, better is to setVisibility(View.GONE) for the elements that should disappear. – Zelimir May 10 '11 at 14:06
  • There's nothing wrong with just taking a screenshot before-hand if it will do the job. It's how iPhone apps "load" so quickly. – Joseph Earl May 10 '11 at 14:30
  • see http://stackoverflow.com/questions/28657088/how-to-get-the-drawable-from-relative-layout-in-android for a complete answer which has an alternative for below answer which did not work for me. – Andreas Weber Feb 24 '16 at 11:38

1 Answers1

10

A simple version:

Bitmap snapshot = null;
    Drawable drawable = null;
    yourView.setDrawingCacheEnabled(true);
    yourView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW); //Quality of the snpashot
    try {
        snapshot = Bitmap.createBitmap(yourView.getDrawingCache(), sizes and stuff); // You can tell how to crop the snapshot and whatever in this method
        drawable = new BitmapDrawable(snapshot)
    } finally {
        yourView.setDrawingCacheEnabled(false);
    }
Alex Orlov
  • 18,077
  • 7
  • 55
  • 44
  • Thanks for the reply, but yourView.getDrawingCache() returns null. – Gratzi May 11 '11 at 06:15
  • Make sure you get this bitmap after yourView.setDrawingCacheEnabled(true); And if you get bitmap as simply as that (without copying it and stuff) and then set yourView.setDrawingCacheEnabled(false); it will become null since cache was disabled. – Alex Orlov May 11 '11 at 06:19
  • I am using the above code exactly, with some dimension values for the new drawable. – Gratzi May 11 '11 at 06:35
  • Strange. It's working fine for me. Where have you placed this code? Note, that it must be called after the view has rendered, so onCreate() isn't the right option. – Alex Orlov May 11 '11 at 09:19
  • You should also try debugging, or call createBitmap without any size params, and check if it'll work. – Alex Orlov May 11 '11 at 09:21