0

I need to take a screenshot from a webview as a thumb, but when I use View.draw(Canvas) I only get the drawing from the top left of the website, not my currently viewing part (what the webview is showing), and also the part out of sight is blank (I know it is caused by enableSlowWholeDocumentDraw and I don't need those area anyway) enter image description here

Here are the related codes (inside a class extends WebView):

public Bitmap Screenshot() {
    try {
        Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(),getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        this.draw(canvas);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
C.H.
  • 191
  • 3
  • 8
  • 1
    You can see the solution given at https://stackoverflow.com/questions/10650049/taking-a-screenshot-of-a-specific-layout-in-android. – Hari N Jha Jun 21 '19 at 07:51
  • unfortunately buildDrawingCache was deprecated https://developer.android.com/reference/android/view/View.html#buildDrawingCache(boolean) – C.H. Jun 21 '19 at 07:58

1 Answers1

1

nvm, I figured it out /s

Turns out Canvas can set Matrix to move the "drawing part" around, so I can use setTranslate(dx,dy) to match the "viewing part"

Updated code:

public Bitmap Screenshot() {
    try {
        Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth(),getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Matrix drawMatrix = new Matrix();
        drawMatrix.setTranslate(-getScrollX(),-getScrollY());
        canvas.setMatrix(drawMatrix);
        this.draw(canvas);
        return bitmap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
C.H.
  • 191
  • 3
  • 8