0

嗨 StackOverflow 社区,

在我的应用程序中,我想要一个允许用户捕获当前视图的按钮。

出于这个原因,我编写了以下方法(面向:Android save view to jpg or png):

private LinearLayout container; 

public void createImageOfCurrentView(View v) {
    if (isExternalStoragePresent()) {
        container = (LinearLayout) findViewById(R.id.container);
        container.setDrawingCacheEnabled(true);
        Bitmap b = container.getDrawingCache();

        File dir = new File(Environment.getExternalStorageDirectory().getPath()
          + "/" + getPackageName() + "/");
        dir.mkdirs();

        File file = new File(dir, "image.jpg");
        FileOutputStream fos;

        try {
            fos = new FileOutputStream(file);
            b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
            Toast.makeText(this, "The current view has been succesfully saved "
              + "as image.", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "Unfortunatly an error occured and this "
              + "action failed.", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(this, "Bacause of lacking access to the storage "
          + "of this device, the current view couldn't be saved as an image.",
          Toast.LENGTH_LONG).show();
    }
}

问题是根据尝试LogCat创建. 所以可能该方法不起作用。在手机上生成文件。但是,大小为 0 字节且没有可见图像。我将不胜感激任何我必须做的建议,以使其按我的意愿工作。NullPointerExceptionjpegcontainer.getDrawingCache()

4

2 回答 2

0

尝试一下 -

public static Bitmap convertViewToBitmap(View view) {
   Bitmap result = null;

   try {
      result = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
      view.draw(new Canvas(result));
   }catch(Exception e) {}    
   return result;
}
于 2012-04-16T08:58:55.703 回答
0

尝试一下 -

view.setDrawingCacheEnabled(true);
Bitmap = bm = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
于 2013-04-08T07:50:03.830 回答