使用 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
相关推荐
阿pin7 小时前
Android随笔-kotlin withContext
android·kotlin·withcontext
树码小子7 小时前
开启 IDEA 中的断言功能
android·java·intellij-idea
Kslient7 小时前
HeaderBehavior
android
Android-Flutter9 小时前
android 动画详解
android·kotlin
小孔龙14 小时前
GraphicBuffer 跨进程共享
android
行业研究员14 小时前
Android内置GPS与腾讯地图定位技术对比分析
android·android定位·腾讯地图定位
Android-Flutter15 小时前
android WMS 详解(二)
android·kotlin
游戏开发爱好者816 小时前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者817 小时前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
阿pin17 小时前
Android随笔-kotlin 高阶函数
android·kotlin·高阶函数