如何将视图转换为Drawable?

Jam*_*mes 9 android

我有一个View,我想将其转换为图像,以便将其存储在某个地方.但是如何将其转换View为图像?

Nir*_*tel 9

试试这个拍摄视图并存储在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();
    }
}
Run Code Online (Sandbox Code Playgroud)


pum*_*kee 5

  1. 在视图上启用绘图缓存:

    view.setDrawingCacheEnabled(true);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 从缓存中创建位图:

    bitmap = Bitmap.createBitmap(view.getDrawingCache());
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在任何地方保存位图...

  4. 禁用绘图缓存:

    view.setDrawingCacheEnabled(false);
    
    Run Code Online (Sandbox Code Playgroud)

  • 我得到了一个**NullPointerException**这个代码行`Bitmap bm = Bitmap.createBitmap(view.getDrawingCache());`可能是什么原因? (2认同)