You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何保存更新后的Layout为PNG?绘图缓存未更新问题

解决Layout内容更新后保存PNG仍为旧内容的问题

问题出在DrawingCache的复用机制上——默认情况下,buildDrawingCache()会复用已存在的缓存,Layout内容更新后不清除旧缓存的话,拿到的还是之前的Bitmap。

修改代码,在生成新缓存前先清除旧缓存,同时在操作完成后释放缓存资源,避免内存泄漏:

// 先清除旧缓存
picLayout.destroyDrawingCache();
// 重新开启缓存并构建
picLayout.setDrawingCacheEnabled(true);
picLayout.buildDrawingCache();
Bitmap bmCA = picLayout.getDrawingCache();

File file = new File(Environment.getExternalStorageDirectory(), folder_1_n);
if (!file.exists()) {
    file.mkdirs();
}

if (file.exists()) {
    FileOutputStream outputStream;
    File outFile = new File(file, c_filename);
    try {
        outputStream = new FileOutputStream(outFile);
        bmCA.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        outputStream.flush();
        outputStream.close();
        // 操作完成后释放缓存资源
        picLayout.setDrawingCacheEnabled(false);
        if (!folder) Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        // 异常情况下也要释放缓存
        picLayout.setDrawingCacheEnabled(false);
    }
} else {
    Toast.makeText(this, "目录创建失败", Toast.LENGTH_SHORT).show();
}

关键修改点:

  • 调用picLayout.destroyDrawingCache()清除旧缓存,确保构建新缓存时基于最新的Layout内容
  • 在操作完成(包括异常场景)后调用picLayout.setDrawingCacheEnabled(false)关闭缓存并释放资源,避免内存占用和后续缓存复用问题

内容的提问来源于stack exchange,提问作者ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:29:59