使用 MaterialShapeDrawable 自定义各种形状的 View

在 Android 开发中,会经常遇到这样的 UI 需求:

  • 制作一个带有特定圆角的按钮
  • 实现一个对话框气泡、标签或胶囊形状
  • 创建复杂形状如梯形、切角卡片等

传统做法通常有两个方向:

  • 使用自定义 Drawable(如 shape.xml),功能有限,难以灵活控制每个角和阴影
  • 使用 Canvas 自行绘制,灵活但实现复杂

其实,Material Design 组件库早已为我们准备好了一套功能强大、使用便捷的解决方案------MaterialShapeDrawable。

它是官方提供的核心绘图工具,支持构建任意角的圆角或切角形状,并内建对描边、阴影、动态变化等效果的支持。借助直观的 API,我们无需深入底层绘制逻辑,就能快速实现复杂而优雅的 UI 外观。

实战案例:创建各种形状的 View

示例 1:四个角全是圆角

js 复制代码
val shapeDrawable = MaterialShapeDrawable(
    ShapeAppearanceModel.Builder()
        .setAllCornerSizes(50f) // 所有角设置为 50px 圆角
        .build()
).apply {
    setTint(Color.RED)
}
view.background = shapeDrawable

示例 2:左上角切角,其他圆角

js 复制代码
val shapeDrawable = MaterialShapeDrawable(
    ShapeAppearanceModel.Builder()
        .setTopLeftCorner(CornerFamily.CUT, 30f)
        .setTopRightCorner(CornerFamily.ROUNDED, 20f)
        .setBottomRightCorner(CornerFamily.ROUNDED, 20f)
        .setBottomLeftCorner(CornerFamily.ROUNDED, 20f)
        .build()
).apply {
    setTint("#FF6200EE".toColorInt())
}
view.background = shapeDrawable

示例3:圆形按钮

js 复制代码
val shapeDrawable = MaterialShapeDrawable(
    ShapeAppearanceModel.Builder()
        .setAllCornerSizes(RelativeCornerSize(0.5f)) // 50%圆角
        .build()
).apply {
    setTint(Color.RED)
}
view.background = shapeDrawable

示例4:带描边按钮

js 复制代码
val shapeDrawable = MaterialShapeDrawable(
    ShapeAppearanceModel.Builder()
        .setAllCornerSizes(50f) // 所有角设置为 50px 圆角
        .build()
).apply {
    strokeWidth = 3f
    strokeColor = ColorStateList.valueOf(Color.GREEN)
    setTint(Color.RED)
}
view.background = shapeDrawable
相关推荐
贺biubiu16 小时前
2025 年终总结|总有那么一个人,会让你千里奔赴...
android·程序员·年终总结
xuekai2008090117 小时前
mysql-组复制 -8.4.7 主从搭建
android·adb
nono牛18 小时前
ps -A|grep gate
android
未知名Android用户19 小时前
Android动态变化渐变背景
android
nono牛20 小时前
Gatekeeper 的精确定义
android
stevenzqzq21 小时前
android启动初始化和注入理解3
android
城东米粉儿1 天前
compose 状态提升 笔记
android
粤M温同学1 天前
Android 实现沉浸式状态栏
android
ljt27249606611 天前
Compose笔记(六十八)--MutableStateFlow
android·笔记·android jetpack