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

问题描述 投票:6回答:3

我用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);

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

android image caching view
3个回答
12
投票

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

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

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


8
投票

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

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是所需的背景颜色。


2
投票

使用下面的代码获取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;
}
© www.soinside.com 2019 - 2024. All rights reserved.