Take screenshot on a View - Android User Interface

Android examples for User Interface:ScreenShot

Description

Take screenshot on a View

Demo Code


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;
import android.view.View.MeasureSpec;

public class Main {
  public static Bitmap screenshot(View view) {
    view.setDrawingCacheEnabled(true);//from  ww w .  j  av  a  2s . c  o m
    Bitmap b = view.getDrawingCache();
    if (b != null)
      return b;
    else {
      view.setDrawingCacheEnabled(true);
      view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
          MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
      view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
      view.buildDrawingCache(true);
      Bitmap cache = view.getDrawingCache();
      if (cache == null) {
        return loadBitmapFromView(view);
      } else {
        b = Bitmap.createBitmap(cache);
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false); // clear drawing cache
        return b;
      }
    }
  }

  public static Bitmap loadBitmapFromView(View v) {
    int w = v.getWidth(); // v.getLayoutParams().width
    int h = v.getHeight(); // v.getLayoutParams().height
    Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
    Canvas c = new Canvas(b);
    v.layout(0, 0, w, h);
    v.draw(c);
    return b;
  }
}

Related Tutorials