获取黑色屏幕截图

问题描述 投票:0回答:1

基本上,我想截取整个scrollView的截图。我尝试了很多方法,但找不到完美的方法。

我试过以下:

public void takeScreenShot() {
    mbitmap = getBitmapOFRootView();
    createImage(mbitmap);
}

public void createImage(Bitmap bmp) {

    String path = Environment.getExternalStorageDirectory().toString() + "/screenshot.jpg";
    try {
        FileOutputStream outputStream = new FileOutputStream(new File(path));
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public Bitmap getBitmapOFRootView() {
    mScrollView.setDrawingCacheEnabled(true);
    int totalHeight = mScrollView.getChildAt(0).getHeight();
    int totalWidth = mScrollView.getChildAt(0).getWidth();
    mScrollView.layout(0,0, totalWidth, totalHeight);
    mScrollView.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(mScrollView.getDrawingCache());
    mScrollView.setDrawingCacheEnabled(false);
    return b;
}

这个方法几乎可以工作,但它只显示了2个视图和一个按钮,除了整个屏幕是黑色的:

Current ScreenShot

我的xml包含很多视图,它的视图层次结构是这样的:

<ScrollView>
   <ConstraintLayout>
     <Views>
      ....
     <Views>
   </ConstraintLayout>
</ScrollView>

我已经提到了很多StackOverflow帖子,但它没有用。那么任何人都可以帮助我吗?

更新:终于找到了解决方案。所以,这是一个背景问题,通过绘制画布来解决它。如下所示:

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);

    return bitmap;
android scrollview screenshot android-bitmap
1个回答
0
投票

你应该使用相同的画布

public static Bitmap saveBitmapFromView(View view, int width, int height) {
 Bitmap bmp = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);                
 Canvas canvas = new Canvas(bmp);
 view.layout(0, 0, view.getLayoutParams().width, view.getLayoutParams().height);
 view.draw(canvas);
 return bmp;
}
© www.soinside.com 2019 - 2024. All rights reserved.