我想将 Jetpack compose 发出的 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 中与此等效的是什么?
有一个新的多平台 Kotlin 库(还支持 Android Views 和 Compose Multiplatform):Comshot
可以在tests中从可组合项中截取屏幕截图。
要在生产代码中截取屏幕截图,请参阅这个问题和这个问题。
首先,确保构建脚本中有以下依赖项(以及其他必需的 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 提供的这个。
我会看看 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。您可以在
AndroidHelpers.kt中找到
captureToImage()
。
您还可以在这里找到 ImageBitmap.kt,其中 asAndroidBitmap() 仅确保 ImageBitmap 的底层“通用”版本实际上是 Android 上的
android.graphics.Bitmap
(这是为了使代码更加平台化)不可知,因此它也可以在 JVM/桌面上运行)