我的目标是测试我的可组合物的颜色。由于某种原因,下面的断言在特定设备/可组合上失败(例如,Composable1 在 Device1 和 Emulator1 上传递,Composable2 在 Device1 上失败,但在 Emulator1 上传递)。颜色差异很小(例如#3F3C34 / #403C34)。这个问题的原因可能是什么?除了允许颜色断言略有不同之外,有什么方法可以获得一致的结果?
internal fun SemanticsNodeInteraction.assertColorAtRelativePositionStrict(
expected: Color,
@FloatRange(from = 0.0, to = 1.0) xPercentage: Float,
@FloatRange(from = 0.0, to = 1.0) yPercentage: Float,
): SemanticsNodeInteraction {
val bitmap = captureToImage().asAndroidBitmap()
val x = ((bitmap.width - 1) * xPercentage).roundToInt()
val y = ((bitmap.height - 1) * yPercentage).roundToInt()
val capturedColor = bitmap.getColor(x, y)
assert(capturedColor == expected) {
"Captured color was ${capturedColor.toArgb().toHexString()} " +
"but expected ${expected.toArgb().toHexString()}."
}
return this
}
private fun Int.toHexString() = String.format("#%06X", (0xFFFFFF and this))
compoasable 中使用的预期颜色和颜色是从 colors.xml 中获取的。