getDrawingCache始终返回相同的Bitmap

Ben*_*oot 8 android bitmap rootview

我目前正在开发一个需要显示带有灰色(黑/白)背景的对话框的项目.为了达到这个目的,我将截取屏幕截图和整个应用程序,将此屏幕截图放在全屏对话框的背景上,并在其上放置一个ColorFilter,使其变灰.

这是第一次完美的工作,但如果我滚动下面的内容并再次请求对话框,它会显示与之前相同的背景.

我用的代码是:

Bitmap bitmap;
View rootView = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
rootView.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
imageView.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)

换句话说,getDrawingCache()始终返回应用程序的相同屏幕截图.

Nil*_*ter 23

我认为这是因为你的旧Bitmap仍在你的绘图缓存中.因此,您首先需要从缓存中删除它,然后将新Image放入缓存中.看看这个问题,似乎是在同一主题上:

删除图纸缓存

编辑: 所以,这是代码,对我有用.我使用Button来保存位图,然后将位图设置为图像视图:

private View rootView;
private ImageView bitmapView;
private Button switchButton;
public Bitmap capturedScreen;
public boolean bitmapNeeded = false;

...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // do the other stuff
    rootView.setDrawingCacheEnabled(true); //enable Drawing cache on your view
    switchButton.setOnClickListener(this);
}

...

@Override
public void onClick(View v) {
    if (v == switchButton) { //when the button is clicked
        captureScreen();
    }
}

public void captureScreen() {
    rootView.buildDrawingCache();       
    capturedScreen = Bitmap.createBitmap(rootView.getDrawingCache());
    imageView.setImageBitmap(capturedScreen);
    rootView.destroyDrawingCache();
}

.... 

//In the onDraw method of your View:
@Override
protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(capturedScreen, 0, 0, paint);
}
Run Code Online (Sandbox Code Playgroud)

这是它的工作原理:每次用户单击按钮时,内部的所有内容都rootView将保存为位图,然后绘制到imageView.当然,如果需要,您可以从代码中的任何位置调用captureScreen方法.

我希望这个例子可以帮到你.