Android implements the method of saving View as Bitmap

  • 2021-07-26 08:51:28
  • OfStack

In this paper, the method of saving View into Bitmap by Android is described as an example. Share it for your reference, as follows:

1.


public Bitmap convertViewToBitmap(View view){
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
        Bitmap.Config.ARGB_8888);
    // Utilization bitmap Generate canvas 
    Canvas canvas = new Canvas(bitmap);
    // Put view Draws the contents in the canvas 
    view.draw(canvas);
  return bitmap;
}

2.


/**
* save view as a bitmap
*/
private Bitmap saveViewBitmap(View view) {
// get current view bitmap
  view.setDrawingCacheEnabled(true);
  view.buildDrawingCache(true);
  Bitmap bitmap = view.getDrawingCache(true);
  Bitmap bmp = duplicateBitmap(bitmap);
  if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); bitmap = null; }
  // clear the cache
  view.setDrawingCacheEnabled(false);
  return bmp;
}
public static Bitmap duplicateBitmap(Bitmap bmpSrc)
{
  if (null == bmpSrc)
    { return null; }
  int bmpSrcWidth = bmpSrc.getWidth();
  int bmpSrcHeight = bmpSrc.getHeight();
  Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Config.ARGB_8888); if (null != bmpDest) { Canvas canvas = new Canvas(bmpDest); final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
  canvas.drawBitmap(bmpSrc, rect, rect, null); }
  return bmpDest;
}

For more readers interested in Android related contents, please check the topics on this site: "Summary of Android File Operation Skills", "Summary of SD Card Operation Methods for Android Programming Development", "Introduction and Advanced Tutorial for Android Development", "Summary of Android Resource Operation Skills", "Summary of Android View View Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: