将像素转换为 Dp 以在 Jetpack Compose 中点击自定义圆形指示

Convert Pixel to Dp for Custom Rounded Indication Clickable in Jetpack Compose

我想在单击按钮时显示自定义指示。指示应在角落处变圆并覆盖较深的颜色。到目前为止,我能够通过以下代码实现这一点

Modifier.clickable(onClick = {}, indication = PressedIndication)
object PressedIndication : Indication {

    private object DefaultIndicationInstance : IndicationInstance {
        override fun ContentDrawScope.drawIndication(interactionState: InteractionState) {
            drawContent()
            if (interactionState.contains(Interaction.Pressed)) drawRoundRect(
                cornerRadius = CornerRadius(4f, 4f), //<-- How to use dp values?
                color = Color.Black.copy(
                    alpha = 0.3f
                ), size = size
            )

        }
    }

    override fun createInstance(): IndicationInstance {
        return DefaultIndicationInstance
    }
}

我可以使用 drawRoundRectcornerRadius 实现圆角,但是有什么方法可以使用 dp 值吗?

注意:我无法使用clickableclip,因为可点击区域与指示区域不完全匹配

你可以通过Dp,但你必须调整屏幕的密度。密度范围代码块内的扩展函数 Dp.toPx() 工作正常。

val sizeInPx = with(LocalDensity.current) { 16.dp.toPx() }

所述,您可以使用 Dp.toPx() 进行转换。

在您的情况下,您可以避免构建自定义 Indication
你可以使用类似的东西:

 val interactionSource = remember { MutableInteractionSource() }
 Modifier.clickable(
        interactionSource = interactionSource,
        indication = rememberRipple(
             radius = 4.dp,
             color=Color.Black.copy(alpha = 0.3f))
        )