我正在使用 kotlin 和 jetpack compose 在 android studio 中制作一个应用程序。我想设置一个不适合每个设备屏幕的背景,以便无论在分辨率为 1235x2345 还是 1080x1920 的设备上,它都保持相同的外观。到目前为止,在适应不同设备时背景会变形。我不知道这是否可能。例子:
您可以使用 Modifier.drawBehind/drawWithContent 以像素为单位(而不是 dp 或密度独立像素)绘制矩形或任何形状。
您可以自定义它以添加垂直或水平偏移。
fun Modifier.drawBackgroundInPx(
color: Color,
width: Int,
height: Int,
style: DrawStyle = Fill
) = this.then(
Modifier.drawBehind {
val canvasWidth = size.width
val canvasHeight = size.height
val startX = (canvasWidth - width) / 2
val startY = (canvasHeight - height) / 2
drawRect(
color = color,
topLeft = Offset(startX, startY),
size = Size(width.toFloat(), height.toFloat()),
style = style
)
}
)
并将其用作
@Preview
@Composable
fun Test() {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Red)
.drawBackgroundInPx(color = Color.Yellow, 1080, 1920)
.drawBackgroundInPx(color = Color.Green, 800, 1200, style = Stroke(20f))
)
}
作为旁注,描边也将宽度视为像素。如果您想使用 LocalDensity.current,您可能需要将其转换为 dp。