将帧布局转换为图像并保存

时间:2014-02-12 10:56:54

标签: android android-framelayout

任何人都可以帮助我了解如何将FrameLayout的内容捕获到图像中并将其保存到内部或外部存储中。

2 个答案:

答案 0 :(得分:33)

尝试将视图(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" />

答案 1 :(得分: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();
    }
}