使用 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
相关推荐
天空之城--5 小时前
Android Koin 完全指南:从原理到实践
android
zhangphil6 小时前
Android main thread主线程Choreographer doFrame发生FullSuspendCheck
android
TimeFine10 小时前
智能眼镜开发:获取真实的音频路由
android
pengyu10 小时前
【Kotlin 协程修仙录 · 渡劫境 · 中阶】 | 造化神兵:自定义 CoroutineDispatcher 与调度器的终极定制
android·kotlin
pengyu10 小时前
【Kotlin 协程修仙录 · 渡劫境 · 初阶】 | 飞升雷劫:CPS 变换与挂起函数字节码终极透视
android·kotlin
TimeFine10 小时前
智能眼镜开发:眼镜Touch后收音与触发播放系统音乐的矛盾处理
android
TimeFine11 小时前
智能眼镜开发:眼镜侧收集音频
android
又见情义11 小时前
Android 系统设置从平板版迁移至TV版实践
android
杉氧14 小时前
打破边界(一):实战编写 Android/iOS 原生模块 (Native Modules)
android·react native·前端框架