Android 如何将视图转换为可绘制视图?

Android 如何将视图转换为可绘制视图?,android,Android,我有一个视图,我想把它转换成一个图像,以便存储在某个地方。 但是如何将此视图转换为图像 在视图上启用图形缓存: view.setDrawingCacheEnabled(true); 从缓存创建位图: bitmap = Bitmap.createBitmap(view.getDrawingCache()); 在任何位置保存位图 禁用图形缓存: view.setDrawingCacheEnabled(false); 尝试此操作以拍摄视图的图像并存储在sd卡中 View view = Te

我有一个
视图
,我想把它转换成一个图像,以便存储在某个地方。 但是如何将此
视图
转换为图像

  • 在视图上启用图形缓存:

    view.setDrawingCacheEnabled(true);
    
  • 从缓存创建位图:

    bitmap = Bitmap.createBitmap(view.getDrawingCache());
    
  • 在任何位置保存位图

  • 禁用图形缓存:

    view.setDrawingCacheEnabled(false);
    

  • 尝试此操作以拍摄视图的图像并存储在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();
        }
    }
    
    我得到了这个代码行的NullPointerException
    Bitmap bm=Bitmap.createBitmap(view.getDrawingCache())原因是什么?