【问题标题】:Convert frame layout into image and save it [closed]将框架布局转换为图像并保存[关闭]
【发布时间】:2014-03-10 15:49:39
【问题描述】:

谁能帮助我了解如何将FrameLayout 的内容捕获到图像中并将其保存到内部或外部存储中。

【问题讨论】:

  • 你的意思是打印屏幕?
  • 没有。将布局转换为图像..
  • FrameLayout 是布局,图像是图像。它们完全不同。我怎样才能把苹果变成橘子?

标签: android android-framelayout


【解决方案1】:

尝试将视图(帧布局)转换为位图:

public Bitmap viewToBitmap(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

然后,将您的位图保存到文件中:

try {
        FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

不要忘记在你的 AndroidManifest.xml 中设置写入存储的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

【讨论】:

  • 非常感谢...成功了...
  • 一定要关闭流,以防出现异常;我建议添加一个finally 块来关闭流并回收位图。
  • 用同样的方法保存图像,但图像全黑不知道我犯了什么错误..
  • 所以我使用框架布局进行了此操作,但无法获得宽度和高度,使用 ViewTreeObserver 我能够在从 onCreate 内部渲染后获取信息。这非常感谢您。欲了解更多信息,请参阅stackoverflow.com/a/8171014/1815624
  • 您可以通过调用view.getDrawingCache(true/false) 来提高效率,因为视图绘图可能已经被缓存。然后,如果 getDrawingCache() 返回 null,请调用 Bitmap.createBitmap()。有关更多信息,请参阅文档:developer.android.com/reference/android/view/…
【解决方案2】:

试试这个...

public static void saveFrameLayout(FrameLayout frameLayout, String path) {
    frameLayout.setDrawingCacheEnabled(true);
    frameLayout.buildDrawingCache();
    Bitmap cache = frameLayout.getDrawingCache();
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        cache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        frameLayout.destroyDrawingCache();
    }
}

【讨论】:

  • 感谢...为您的努力..
  • @Gopal Gopi 我尝试使用 framelayout 但我一直将 framelayout 宽度作为屏幕尺寸我该如何解决它
  • @pcpriyanka 如果您的 framelayout 尺寸与 match_parent 相同,您将只获得屏幕尺寸
  • @GopalGopi 那么应该是什么?
  • 现在是fill_parent
猜你喜欢
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 2015-11-03
  • 2020-03-04
  • 1970-01-01
  • 2021-06-09
相关资源
最近更新 更多