如何将View转换为Drawable?

10

我有一个 View,想把它转换成图片以便于存储。但是,我该如何将这个 View 转换为图片呢?

2个回答

10

尝试以下步骤,以便拍摄视图并将其存储在SD卡中。

View view = TextView.getRootView();
//You can use any view of your View instead of TextView

if (view != null)
{
    System.out.println("view is not null.....");
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bm = view.getDrawingCache();

    try
    {
        if (bm != null)
        {
            String dir = Environment.getExternalStorageDirectory().toString();
            System.out.println("bm is not null.....");
            OutputStream fos = null;
            File file = new File(dir,"sample.JPEG");
            fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            bos.flush();
            bos.close();
        }
    }
    catch(Exception e)
    {
        System.out.println("Error="+e);
        e.printStackTrace();
    }
}

5
  1. Enable drawing cache on the view:

    view.setDrawingCacheEnabled(true);
    
  2. Create a bitmap from the cache:

    bitmap = Bitmap.createBitmap(view.getDrawingCache());
    
  3. Save the bitmap wherever...

  4. Disable drawing cache:

    view.setDrawingCacheEnabled(false);
    

5
这行代码 Bitmap bm = Bitmap.createBitmap(view.getDrawingCache()); 出现了 NullPointerException 错误,可能的原因是什么? - AnujAroshA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接