如何使用Jetpack Compose创建圆角边框按钮

77

我需要使用Jetpack Compose在按钮中添加带圆角的边框。

例如:

enter image description here

6个回答

117
要实现一个带有圆角边框的按钮,您可以使用OutlinedButton组件,在shape参数中应用RoundedCornerShape
OutlinedButton(
    onClick = { },
    border = BorderStroke(1.dp, Color.Red),
    shape = RoundedCornerShape(50), // = 50% percent
                                    // or shape = CircleShape
    colors = ButtonDefaults.outlinedButtonColors(contentColor = Color.Red)
){
    Text( text = "Save" )
}

enter image description here

它适用于M2和M3。


1
谢谢您先生,但我想要一个带有圆角边框的自定义UI。 - Sanjayrajsinh
@Sanjayrajsinh OutlinedButtonStyle 默认拥有圆角。然而,你可以使用 shape = RoundedCornerShape(x.dp) 以覆盖默认值。 - Gabriele Mariotti
1
@Sanjayrajsinh 或者使用 shape = RoundedCornerShape(50) 的百分比值。我刚刚更新了答案。 - Gabriele Mariotti
@GabrieleMariotti 我看不出Button()和OutlinedButton()之间有什么区别。如果我使用相同的代码与Button()一起使用,它将给出相同的结果。请问它们之间有什么区别? - Ranjithkumar
1
@RanjithKumar OutlinedButton 是一个带有 outlinedBorder 和自定义颜色的 Button,其中 backgroundColor= MaterialTheme.colors.surfacecontentColor = MaterialTheme.colors.primary - Gabriele Mariotti

51

只需使用修饰符:

modifier = Modifier.border( width = 2.dp,
                            color = Color.Red,
                            shape = RoundedCornerShape(5.dp))

21

使用Clip修饰符,此外您还可以选择特定的角来使其弯曲。

 modifier = Modifier.clip(RoundedCornerShape(15.dp, 15.dp, 0.dp, 0.dp))

18
使用clip修饰符。 Modifier.clip(CircleShape)

7

这是您在该图片中看到的按钮:

Button(
       onClick = {},
       shape = RoundedCornerShape(23.dp),
       border = BorderStroke(3.dp, Color.Red),
       colors = ButtonDefaults.buttonColors(contentColor = Color.Red, backgroundColor = Color.White)
       ) {
            Text(
                text = "Save",
                fontSize = 17.sp,
                modifier = Modifier.padding(horizontal = 30.dp, vertical = 6.dp)
            )
        }

1
在 Material 3 中使用 shape = RoundedCornerShape(23.dp) 就能轻松实现圆角效果! - Daniele Ceglia

4

试试这个

               Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .padding(4.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color.White)
                        .border(
                            1.dp,
                            Color.RED,
                            shape = RoundedCornerShape(8.dp),
                        )

                ) {
                    Text(
                        modifier = Modifier.align(Alignment.Center),
                        text = "Save",
                        color = Color.RED,
                        style = MaterialTheme.typography.h6
                    )
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接