如何在Jetpack Compose中制作带底部短斜角的按钮?
在Jetpack Compose中实现底部带短斜角的按钮
要实现这种底部带短斜角的按钮,核心是自定义Shape来绘制按钮的轮廓,具体步骤如下:
1. 自定义底部斜角Shape类
创建一个继承自Shape的类,通过Path绘制出带底部斜角的轮廓:
import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.density class BottomCutCornerShape(private val cutSize: Dp) : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { // 将Dp转换为像素值 val cutPx = with(density) { cutSize.toPx() } val path = Path().apply { // 绘制轮廓路径:左上角→右上角→右上斜角起点→右下斜角终点→左下斜角终点→左上斜角起点→闭合 moveTo(0f, 0f) lineTo(size.width, 0f) lineTo(size.width, size.height - cutPx) lineTo(size.width - cutPx, size.height) lineTo(cutPx, size.height) lineTo(0f, size.height - cutPx) close() } return Outline.Generic(path) } }
2. 在Button中使用自定义Shape
直接将自定义的BottomCutCornerShape传给Button的shape参数即可:
import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun CutCornerButton() { Button( onClick = { /* 处理点击事件 */ }, shape = BottomCutCornerShape(cutSize = 8.dp), // 调整cutSize控制斜角大小 colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF2D7CFF)), modifier = Modifier.padding(16.dp) ) { Text(text = "示例按钮", color = Color.White) } }
你可以通过修改cutSize的值来调整底部斜角的长度,数值越大斜角越明显。
内容的提问来源于stack exchange,提问作者AmazingHorsess
相关产品推荐
相关产品推荐

