使用 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
相关推荐
lichong95111 小时前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之android 把assert里的dist.zip 包解压到sd卡里
android·vue.js·iphone
·云扬·12 小时前
MySQL 日志全解析:Binlog/Redo/Undo 等 5 类关键日志的配置、作用与最佳实践
android·mysql·adb
Kapaseker12 小时前
如果你的 View 不支持 Compose 怎么办
android·kotlin
珹洺13 小时前
Java-Spring入门指南(五)Spring自动装配
android·java·spring
sylvia_081513 小时前
react native 初次使用Android Studio 打包
android·react native·android studio
前行的小黑炭13 小时前
Android:在项目当中可能会遇到的ANR,应该如何解决?
android·java·kotlin
老衲不服17 小时前
android 三方sdk minSdkVersion 兼容问题处理
android
android_xc21 小时前
Android Studio国内仓库配置
android·ide·android studio
alexhilton21 小时前
runBlocking实践:哪里该使用,哪里不该用
android·kotlin·android jetpack
2501_9151063221 小时前
iOS 使用记录和能耗监控实战,如何查看电池电量消耗、App 使用时长与性能数据(uni-app 开发调试必备指南)
android·ios·小程序·uni-app·cocoa·iphone·webview