Screenshot Composables and convert to Bitmap on user action or periodically

Overview

Compose ScreenshotBox

Screenshot Composables and convert to Bitmap on user action or periodically.

Single Shot Periodic

Gradle Setup

To get a Git project into your build:

  • Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:
allprojects {
  repositories {
      ...
      maven { url 'https://jitpack.io' }
  }
}
  • Step 2. Add the dependency
dependencies {
    implementation 'com.github.SmartToolFactory:Compose-Screenshot:Tag'
}

Implementation

Single Shot

Create a ScreenshotBox which covers your Composables you want to take screenshot of

ScreenshotBox(screenshotState = screenshotState) {
    Column(
        modifier = Modifier
            .border(2.dp, Color.Green)
            .padding(5.dp)
    ) {

        Image(
            bitmap = ImageBitmap.imageResource(
                LocalContext.current.resources,
                R.drawable.landscape
            ),
            contentDescription = null,
            modifier = Modifier
                .background(Color.LightGray)
                .fillMaxWidth()
                // This is for displaying different ratio, optional
                .aspectRatio(4f / 3),
            contentScale = ContentScale.Crop
        )

        Text(text = "Counter: $counter")
        Slider(value = progress, onValueChange = { progress = it })
    }
}

Provide a ScreenshotState which stores Bitmap

val screenshotState = rememberScreenshotState()

and take screenshot by clicking a button or calling screenshotState.capture()

Button(
    onClick = { 
        screenshotState.capture()
    }
) { 
    Text(text = "Take Screenshot")
}

And get Bitmap or ImageBitmap as

screenshotState.imageBitmap?.let {
    Image(
        modifier = Modifier
            .width(200.dp)
            .height(150.dp),
        bitmap = it,
        contentDescription = null
    )
}

initially Bitmap is null because onGloballyPositioned might not return correct coordinates or sometimes it returns zero width or height, nullable makes sure that you get the latest one after calling screenshotState.capture()

Periodic Shot

Collect screenshotState.liveScreenshotFlow to get periodic screenshots of your composables with

LaunchedEffect(Unit) {
        screenshotState.liveScreenshotFlow.onEach {
            imageBitmap = it.asImageBitmap()
        }.launchIn(this)
    }

ScreenshotState

Set a delay after each shot by setting delayInMillis

/**
 * Create a State of screenshot of composable that is used with that is kept on each recomposition.
 * @param delayInMillis delay before each screenshot if [liveScreenshotFlow] is collected.
 */
@Composable
fun rememberScreenshotState(delayInMillis: Long = 20) = remember {
    ScreenshotState(delayInMillis)
}

/**
 * State of screenshot of composable that is used with.
 * @param timeInMillis delay before each screenshot if [liveScreenshotFlow] is collected.
 */
class ScreenshotState internal constructor(
    private val timeInMillis: Long = 20
) {
    internal var callback: (() -> Bitmap?)? = null

    private val bitmapState = mutableStateOf(callback?.invoke())

    /**
     * Captures current state of Composables inside [ScreenshotBox]
     */
    fun capture() {
        bitmapState.value = callback?.invoke()
    }

    val liveScreenshotFlow = flow {
        while (true) {
            val bmp = callback?.invoke()
            bmp?.let {
                emit(it)
            }
            delay(timeInMillis)
        }
    }

    val bitmap: Bitmap?
        get() = bitmapState.value

    val imageBitmap: ImageBitmap?
        get() = bitmap?.asImageBitmap()
}

You might also like...
Auto Scrolling Image Pager with Pager Indicator and Text
Auto Scrolling Image Pager with Pager Indicator and Text

AutoImageFlipper Auto Scrolling Image Pager with Pager Indicator and Text Note: It works only on Apps which are using AndroidX dependencies, if you're

This is an Image slider with swipes, Here we used Volley to Image load URL's from JSON! Here we make it very easy way to load images from Internet and We customized the description font style(OpenSans).

ImageSliderWithSwipes This is an Image slider with swipes, Here we used Volley to load URL's from JSON! Here we make it very easy way to load images f

Stingle Photos is a secure, open-source photo, video cloud storage and backup application

Stingle Photos Stingle Photos is a secure, open-source photo, video cloud storage and backup application that is safe, ad-free and easy to use. It pro

An Android project containing image recognition and object detection models.
An Android project containing image recognition and object detection models.

An Android project containing image recognition and object detection models. Users can input images into the deep learning model by taking photos, opening photo albums, and real-time previews on the Android side. After the calculation on the Android side is completed, the model will output the prediction result and show it to the user.

Kotlin extensions of BlurHash for ImageView, Glide, Coil, Piccasso, and fast loading BlurHashDrawable optimized for Android.
Kotlin extensions of BlurHash for ImageView, Glide, Coil, Piccasso, and fast loading BlurHashDrawable optimized for Android.

Kotlin extensions of BlurHash for ImageView, Glide, Coil, Piccasso, and fast loading BlurHashDrawable optimized for Android.

Android Camera Application for Exposure Fusion Algorithm and more
Android Camera Application for Exposure Fusion Algorithm and more

Android Camera Application for Exposure Fusion Algorithm and more

An Android transformation library providing a variety of image transformations for Coil, Glide, Picasso, and Fresco.
An Android transformation library providing a variety of image transformations for Coil, Glide, Picasso, and Fresco.

An Android transformation library providing a variety of image transformations for Coil, Glide, Picasso, and Fresco.

An Android library for scanning documents based on CameraX API and a tiny version of OpenCV

Document Scanner with tiny OpenCV example1.mp4 Document Scanner is an Android library (kotlin based) for scanning documents based on CameraX API and a

Software blur implementation for Blur, blur, and one more time blur article
Software blur implementation for Blur, blur, and one more time blur article

Software Blur Software blur implementation for Blur, blur, and one more time blu

Releases(1.0.3)
  • 1.0.3(May 18, 2022)

    In this version ScreenshotState's bitmapState is set to public visibility to observe directly or set to null if needed in any recompositions to not get previously screenshot ImageBitmap while progress of taking new one hasn't finished.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(May 16, 2022)

  • 1.0.0(Apr 17, 2022)

Owner
Smart Tool Factory
Developer From Thrace fueled with 🍺 ☕️ and 🤘
Smart Tool Factory
[Android] Screenshot detection while user using your app

[Android] Screenshot detection while user using your app

Akexorcist 137 Dec 30, 2022
A small customizable library useful to handle an gallery image pick action built-in your app. :sunrise_over_mountains::stars:

Louvre A small customizable image picker. Useful to handle an gallery image pick action built-in your app. *Images from Google Image Search Installati

André Mion 640 Nov 19, 2022
Library to save image locally and shows options to open and share !

Image Save and Share Library to save image locally and shows options to open and share ! Download Demo APK from HERE Kindly use the following links to

Prabhakar Thota 27 Apr 18, 2022
Add curve at bottom of image views and relative layouts.

Crescento Android library that adds a curve at the below of image views and relative layouts. CrescentoImageView and CrescentoContainer are the image

Shivam Satija 1.3k Nov 18, 2022
Android widget for cropping and rotating an image.

Cropper The Cropper is an image cropping tool. It provides a way to set an image in XML and programmatically, and displays a resizable crop window on

Edmodo 2.9k Nov 14, 2022
Crop and Rounded Corners added to an ImageView.

SuperImageView Extra features for your ImageView provided in a modularized way Documentation for v2 coming this week. CropImageView An ImageView that

César Díez Sánchez 658 Dec 1, 2022
Customizable Android full screen image viewer for Fresco library supporting "pinch to zoom" and "swipe to dismiss" gestures. Made by Stfalcon

This project is no longer supported. If you're able to switch from Fresco to any other library that works with the Android's ImageView, please migrate

Stfalcon LLC 1.8k Dec 19, 2022
Add curve at bottom of image views and relative layouts.

Crescento Android library that adds a curve at the below of image views and relative layouts. CrescentoImageView and CrescentoContainer are the image

Shivam Satija 1.3k Mar 24, 2021
Dali is an image blur library for Android. It contains several modules for static blurring, live blurring and animations.

Dali Dali is an image blur library for Android. It is easy to use, fast and extensible. Dali contains several modules for either static blurring, live

Patrick Favre-Bulle 1k Dec 1, 2022
Awesome Image Picker library will pick images/gifs with beautiful interface. Supports image or gif, Single and Multiple Image selection.

Awesome Image Picker Awesome Image Picker library will pick images/gifs with beautiful interface. Supports image or gif, Single and Multiple Image sel

Prabhakar Thota 162 Sep 13, 2022