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

373 阅读1分钟

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

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

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

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

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

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

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

示例 1:四个角全是圆角

image.png

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

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

image.png

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:圆形按钮

image.png

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

示例4:带描边按钮

image.png

val shapeDrawable = MaterialShapeDrawable(
    ShapeAppearanceModel.Builder()
        .setAllCornerSizes(50f) // 所有角设置为 50px 圆角
        .build()
).apply {
    strokeWidth = 3f
    strokeColor = ColorStateList.valueOf(Color.GREEN)
    setTint(Color.RED)
}
view.background = shapeDrawable