繁体   English   中英

在 Jetpack Compose 中以编程方式截取可组合乐趣的屏幕截图

[英]Take screenshot of a composable fun programmatically in Jetpack Compose

我想将 Jetpack 组合发出的 UI 捕获为位图。 在 XML 中,这是这样完成的:

基本上将视图作为输入参数并将其作为位图返回。

//take screenshot of the view added as an input argument
fun takeScreenShot(view: View) : Bitmap {
    val bitmap = Bitmap.createBitmap(
        view.width,
        view.height,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    view.draw(canvas)
    return bitmap
}

Jetpack compose 中的 this 等价物是什么?

我会看看 JP-Compose 测试是如何做到这一点的。

一个好的起点可能是android-compose-codelab ,请参阅:

/**
 * Simple on-device screenshot comparator that uses golden images present in
 * `androidTest/assets`. It's used to showcase the [AnimationClockTestRule] used in
 * [AnimatingCircleTests].
 *
 * Minimum SDK is O. Densities between devices must match.
 *
 * Screenshots are saved on device in `/data/data/{package}/files`.
 */
@RequiresApi(Build.VERSION_CODES.O)
fun assertScreenshotMatchesGolden(
    goldenName: String,
    node: SemanticsNodeInteraction
) {
    val bitmap = node.captureToImage().asAndroidBitmap()
}

来自ScreenshotComparator.kt 你可以找到captureToImage()在这里的AndroidHelpers.kt

您也可以在这里找到ImageBitmap.kt ,其中asAndroidBitmap()仅确保ImageBitmap的底层“通用”版本实际上是 Android 上的android.graphics.Bitmap (这是为了使代码与平台无关,因此它也可以在 JVM/桌面上运行)

测试中可以从可组合中截取屏幕截图。
要在生产代码中截取屏幕截图,请参阅此问题此问题

首先,确保您的构建脚本中具有以下依赖项(以及其他必需的 Compose 依赖项):

debugImplementation("androidx.compose.ui:ui-test-manifest:<version>")

注意:您可以简单地在androidTest目录中添加一个AndroidManifest.xml并在manifest > application元素中添加以下内容,而不是上述依赖项: <activity android:name="androidx.activity.ComponentActivity" />
参考这个答案

这是保存、阅读和比较屏幕截图的完整示例:
(请参阅此帖子以设置测试的写入权限等)

class ScreenshotTest {

    @get:Rule val composeTestRule = createComposeRule()

    @Test fun takeAndSaveScreenshot() {
        composeTestRule.setContent { MyComposableFunction() }
        val node = composeTestRule.onRoot()
        val screenshot = node.captureToImage().asAndroidBitmap()
        saveScreenshot("screenshot.png", screenshot)
    }

    @Test fun readAndCompareScreenshots() {
        composeTestRule.setContent { MyComposableFunction() }
        val node = composeTestRule.onRoot()
        val screenshot = node.captureToImage().asAndroidBitmap()

        val context = InstrumentationRegistry.getInstrumentation().targetContext
        val path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val file = File(path, "screenshot.png")
        val saved = readScreenshot(file)

        println("Are screenshots the same: ${screenshot.sameAs(saved)}")
    }

    private fun readScreenshot(file: File) = BitmapFactory.decodeFile(file.path)

    private fun saveScreenshot(filename: String, screenshot: Bitmap) {
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        // Saves in /Android/data/your.package.name.test/files/Pictures on external storage
        val path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val file = File(path, filename)
        file.outputStream().use { stream ->
            screenshot.compress(Bitmap.CompressFormat.PNG, 100, stream)
        }
    }
}

感谢 Google Codelabs 为此

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM