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

时间:2014-08-19 03:36:55

标签: android image caching view

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

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

3 个答案:

答案 0 :(得分:12)

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

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

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

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

在代码下方使用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;
}