如何绘制内边框?

问题描述 投票:0回答:3

我想在 Column 上画两条边框(1 个在里面 - 1 个在外面)。

预期结果:

Modifier.border(2.dp) // -> this creates inner border.
android kotlin android-jetpack-compose android-jetpack
3个回答
3
投票

你有不同的选择。

  • 你可以简单地应用一个
    border
    修饰符然后一个
    padding
    .

类似的东西:

    val shape = RoundedCornerShape(16.dp)

    Box(modifier = Modifier
        .size(60.dp , 100.dp)
        .border(2.dp, Blue, shape)
        .padding(4.dp)
        .background(Blue, shape)
    ){
      //content
    }

  • 您可以两次应用

    border
    修饰符:

      val shape = RoundedCornerShape(16.dp)
    
      Box(modifier = Modifier
          .size(60.dp , 100.dp)
          .border(2.dp, Blue, shape)
          .border(4.dp, White, shape)
          .background(Blue, shape)
      ){
          //content
      } 
    

  • 最后你可以画一个inner border.

类似的东西:

fun Modifier.innerBorder(
    strokeWidth: Dp,
    color: Color,
    cornerRadiusDp: Dp,
    offset : Offset = Offset.Zero
) = composed(
    factory = {
        val density = LocalDensity.current
        val strokeWidthPx = density.run { strokeWidth.toPx() }
        val cornerRadiusPx = density.run { cornerRadiusDp.toPx() }
        val halfStroke = strokeWidthPx / 2
        val topLeft = Offset(halfStroke + offset.x, halfStroke + offset.y)

        Modifier.drawBehind {
            val width = size.width -  topLeft.x*2  
            val height = size.height - topLeft.y*2              

            drawRoundRect(
                color = color,
                topLeft = topLeft,
                size = Size(width, height),
                cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx).shrink(halfStroke),
                style = Stroke(strokeWidthPx)
            )

        }
    }
)

private fun CornerRadius.shrink(value: Float): CornerRadius = CornerRadius(
    kotlin.math.max(0f, this.x - value),
    kotlin.math.max(0f, this.y - value)
)

然后应用它:

   val shape = RoundedCornerShape(16.dp)

   Column(modifier = Modifier
        .size(60.dp , 100.dp)
        .background( Blue , shape)
        .innerBorder(
            strokeWidth = 2.dp,
            color = White,
            cornerRadiusDp = 16.dp,
            offset = Offset(4f,4f)
        )
    ){
      //....content
    }


1
投票

试试这个:

val shape = RoundedCornerShape(14.dp)
Column(
    modifier = Modifier.width(58.dp).height(78.dp)
        .clip(shape)
        .border(width = 2.dp, color = Color.Blue, shape = shape)
        .border(width = 4.dp, color = Color.White, shape = shape)
        .background(Color.Blue)
) {}

输出:


1
投票

enter image description here

@可组合 有趣的 BorderedBox() {

val shape = RoundedCornerShape(4.dp)
Box(
    modifier = Modifier
        .size(120.dp)
        .border(3.dp, Blue, shape)
        .padding(4.dp)
        .background(Blue, shape)
) {

}

}

© www.soinside.com 2019 - 2024. All rights reserved.