ViewCapture


public final class ViewCapture


Summary

Public methods

static final @NonNull Bitmap
captureToBitmap(@NonNull View receiver, Rect rect)

Suspend function for capturing an image of the underlying view into a Bitmap.

static final @NonNull ListenableFuture<@NonNull Bitmap>

A ListenableFuture variant of captureToBitmap intended for use from Java.

Public methods

captureToBitmap

public static final @NonNull Bitmap captureToBitmap(@NonNull View receiver, Rect rect)

Suspend function for capturing an image of the underlying view into a Bitmap.

For devices below Build.VERSION_CODES#O, the image is obtained using View#draw. Otherwise, PixelCopy is used. Note when PixelCopy is used, the resulting image will be taken from the View's window, then cropped to the approximate location of the View in the window. So depending on window content you may see content from other View's within the resulting image.

This method will also enable HardwareRendererCompat#setDrawingEnabled(boolean) if required.

This API is primarily intended for use in lower layer libraries or frameworks. For test authors, it's recommended to use Espresso's captureToBitmap action or Compose's captureToImage.

If a rect is supplied, this will further crop locally from the bounds of the given view. For example, if the given view is at (10, 10 - 30, 30) and the rect is (5, 5 - 10, 10), the final bitmap will be a 5x5 bitmap that spans (15, 15 - 20, 20). This is particularly useful for Compose, which only has a singular view that contains a hierarchy of nodes.

This API must be called on the View's handler thread. If you're calling this from another context, eg directly from the test thread, you can use something like

{@code
runBlocking(view.handler.asCoroutineDispatcher()) {
    withTimeout(10.seconds) {
      view.captureToBitmap(rect)
    }
}
}

The resulting image is captured after forcing the View to redraw, and waiting for the draw to operation complete. This is done as a means to improve the stability of the resulting image - especially in cases where hardware rendering drawing is off initially.

captureToBitmapAsync

public static final @NonNull ListenableFuture<@NonNull BitmapcaptureToBitmapAsync(@NonNull View receiver, Rect rect)

A ListenableFuture variant of captureToBitmap intended for use from Java.