使用getDrawingCache保存视图位图会显示黑色图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用getDrawingCache保存视图位图会显示黑色图像相关的知识,希望对你有一定的参考价值。

我用setDrawingCacheEnabledgetDrawingCache尝试的一切都没有用。系统正在制作图像,但它看起来只是黑色。

其他人似乎也有类似的问题,但答案似乎太复杂或与我的情况无关。以下是我看过的一些内容:

这是我的代码:

    view.setDrawingCacheEnabled(true);
    Bitmap bitmap = view.getDrawingCache();
    try {
        FileOutputStream stream = new FileOutputStream(getApplicationContext().getCacheDir() + "/image.jpg");
        bitmap.compress(CompressFormat.JPEG, 80, stream);
        stream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    view.setDrawingCacheEnabled(false);

我在下面分享我的答案,以防其他人犯同样的错误。

答案

我的问题是我的viewTextViewTextView上的文字是黑色的(自然),在应用程序中,背景看起来是白色的。但是,后来我回忆起读取视图的背景默认是透明的,以便下面的任何颜色显示出来。

所以我将android:background="@color/white"添加到视图的布局xml中并且它有效。在我看到黑色背景上的黑色文字之前,我一直在查看图像。

请参阅@BraisGabin的答案,了解不需要过度绘制UI的替代方法。

另一答案

我刚刚找到了一个很好的选择:

final boolean cachePreviousState = view.isDrawingCacheEnabled();
final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);

其中0xfffafafa是所需的背景颜色。

另一答案

使用下面的代码获取bitmap图像以查看它工作正常。

 public Bitmap loadBitmapFromView(View v) {
         DisplayMetrics dm = getResources().getDisplayMetrics();
         v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels, 
         View.MeasureSpec.EXACTLY),
         View.MeasureSpec.makeMeasureSpec(dm.heightPixels, 
         View.MeasureSpec.EXACTLY));
         v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
         Bitmap returnedBitmap = 
         Bitmap.createBitmap(v.getMeasuredWidth(),
         v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
         Canvas c = new Canvas(returnedBitmap);
         v.draw(c);

        return returnedBitmap;
}

以上是关于使用getDrawingCache保存视图位图会显示黑色图像的主要内容,如果未能解决你的问题,请参考以下文章

无法将位图保存在手机内存中

解析View的getDrawingCache方法

从 FrameLayout 生成 GIF

如何从视频中捕获位图图像

在 Android 上将视图转换为位图

无法将位图图像获取到图像视图