将任何视图转换为图像并保存

19

请问有谁能帮我了解如何捕获 FrameLayout 内容并将其保存为图像到内部或外部存储器。

如何将任何视图转换为图像?


你的意思是截屏吗? - Raptor
不要转换布局为图像。 - Akshay
FrameLayout 是一种布局,而 image 是一张图片。它们非常不同。我怎么能把一个苹果变成一个橙子? - Raptor
2个回答

39

尝试使用以下方法将视图(FrameLayout)转换为位图:

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" />

非常感谢,它起作用了。 - Akshay
在出现异常的情况下一定要关闭流;我建议添加一个finally块来关闭流并回收位图。 - Paul Lammertsma
同样的方法保存图像,但图像全是黑色。你有什么想法我犯了什么错误吗? - user2273146
我使用了一个FrameLayout,但是无法获取宽度和高度。使用ViewTreeObserver,我能够在onCreate内部渲染后获得信息。这对我的工作非常有帮助。更多信息请参见https://dev59.com/Luo6XIcBkEYKwwoYSCc1#8171014。 - CrandellWS
你可以通过调用 view.getDrawingCache(true/false) 来使其更加高效,因为视图绘制可能已经被缓存。然后,如果 getDrawingCache() 返回 null,则按照你的方式调用 Bitmap.createBitmap()。有关更多信息,请参阅文档:https://developer.android.com/reference/android/view/View.html#getDrawingCache(boolean) - w3bshark
@GhoRiser 我正在尝试使用FrameLayout,但每次我都会得到与屏幕大小相同的FrameLayout宽度,我该如何解决这个问题?/ - PriyankaChauhan

9

试试这个...

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();
    }
}

感谢您的努力。 - Akshay
@Gopal Gopi 我正在尝试使用帧布局,但每次我都会得到屏幕大小的帧布局宽度,我该如何解决这个问题? - PriyankaChauhan
@pcpriyanka 如果你的帧布局尺寸设置为match_parent,那么你将只会得到屏幕尺寸。 - Gopal Gopi
@GopalGopi 那应该是什么? - PriyankaChauhan
现在它是fill_parent。 - PriyankaChauhan
显示剩余2条评论

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