8.1.1 Android 中的 13 种 Drawable 小结 Part 1
系统梳理 Android Drawable 资源命名规范,并详解 ColorDrawable、NinePatchDrawable、ShapeDrawable 与 GradientDrawable 的 XML 属性及 Java 编程用法。
学完这一章,你能够
- 系统梳理 Android Drawable 资源命名规范,并详解 ColorDrawable、NinePatchDrawable、ShapeDrawable 与 GradientDrawable 的 XML 属性及 Java 编程用法。
Drawable 资源分类与命名约束
Android 图形体系内置 13 类常用 `Drawable`,按形态可分为普通位图资源(在 Android Studio 中常放置于 `res/mipmap-*` 或按密度划分的 `res/drawable-*`)和 XML 描述的可绘制资源(放置于 `res/drawable/`,如选择器、形状或渐变)。XML 布局中通过 `@mipmap/xxx` 或 `@drawable/xxx` 引用,Java 代码中可通过 `Resources.getDrawable()`(新 API 推荐 `ContextCompat.getDrawable()`)或控件的 `getDrawable()` 获取实例。资源文件名严格受限为小写字母、数字、下划线与点号 `[a-z0-9_.]` 且不能以数字开头,含大写字母或数字前缀会导致 AAPT 编译报错。
ColorDrawable 与 NinePatchDrawable
`ColorDrawable` 是最基础的纯色绘制对象,绘制时以固定颜色填充整个边界区域。除直接 `new ColorDrawable(0xffff2200)` 或编写 `<color>` 根标签 XML 外,实际工程最常用的是在 `res/values/colors.xml` 集中定义 `<color name="...">` 并在 XML 用 `@color/xxx` 或 Java 用 `getColor()` 引用,也可使用 `Color.BLUE`、`Color.WHITE`(注意标准常量为 `WHITE`)、`android.R.color.*` 或 `Color.argb(a, r, g, b)`。特别要注意:XML 中 `#RRGGBB` 默认不透明,而在 Java 整型字面量中必须显式写出高 8 位透明度(如 `0xFFFF0000` 表示不透明红,若漏写透明度写成 `0xFF0000` 则 Alpha 为 `0x00` 完全透明)。
`NinePatchDrawable`(点九图 `.9.png`)通过图片四边 1px 黑线标记可拉伸区域与内容显示区域,实现不同尺寸控件下的无失真自适应缩放。在 Android Studio 中使用点九图需注意两条硬性要求:必须放在 `res/drawable` 目录而非 `res/mipmap`;原始 `.9.png` 必须保留四周 1px 黑线标记,直接解压 APK 取出的已编译点九图因黑线被写入 PNG 私有块 `npTc`,直接放入工程会导致 AAPT 编译失败,需反编译还原。此外还可通过 `<nine-patch>` 或 `<bitmap>` XML 标签包装点九图并配置 `android:dither`。
ShapeDrawable 与 GradientDrawable 渐变及 Java 扩展
XML 根标签 `<shape>` 实际解析生成 `GradientDrawable` 实例,可定义 `rectangle`(矩形)、`oval`(椭圆)、`line`(线段)与 `ring`(环形,配合 `innerRadius`/`innerRadiusRatio`、`thickness`/`thicknessRatio`、`useLevel` 生效)四种基础几何体。其子节点涵盖 `<size>`(宽高)、`<solid>`(纯色填充,注意 `<solid>` 会覆盖 `<gradient>` 渐变效果)、`<stroke>`(描边宽度、颜色及虚线参数 `dashWidth`/`dashGap`)、`<corners>`(统一 `radius` 或四角独立半径,标准标签名为 `corners` 与 `bottomLeftRadius`/`bottomRightRadius`)及 `<padding>`(四向内边距)。
`<gradient>` 子节点支持三种渐变模式:`linear`(线性渐变,`angle` 必须为 `45` 的整数倍)、`radial`(放射渐变,必须提供 `gradientRadius`)和 `sweep`(扫描渐变),配合 `startColor`、`centerColor`、`endColor` 及范围 `0–1` 的 `centerX`/`centerY` 与 `useLevel` 即可通过 XML 快速组合出丰富的视觉背景(如 `gradient_linear.xml`、`gradient_radial.xml` 与 `gradient_sweep.xml`)。
当需要更复杂的几何轮廓、着色器或路径特效时,可在 Java 中直接构建 `ShapeDrawable` 并传入 `RectShape`、`OvalShape`、`RoundRectShape`、`PathShape`(如菱形路径)或 `ArcShape`,再为 `getPaint()` 配置 `SweepGradient`、`LinearGradient`、`BitmapShader` 以及 `DiscretePathEffect`、`CornerPathEffect`、`ComposePathEffect` 等组合特效。本站离线实验对资源命名正则、ARGB 打包、`<nine-patch>`/`<shape>`/`<gradient>` XML 属性以及 7 个编程 `ShapeDrawable` 的纵排边界与菱形面积进行了逐项校验。
验证 Drawable 命名正则、ARGB 颜色打包、NinePatch/Shape/Gradient XML 属性与 PathShape 布局
"""Offline verification lab for Android Ch 105: tutorial-drawable1."""
import json
import re
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"
NS = "{http://schemas.android.com/apk/res/android}"
COLOR_DRAWABLE_XML = """<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="#FF0000"/>"""
COLORS_VALUES_XML = """<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="material_grey_100">#fff5f5f5</color>
<color name="material_grey_300">#ffe0e0e0</color>
<color name="material_grey_50">#fffafafa</color>
<color name="material_grey_600">#ff757575</color>
<color name="material_grey_800">#ff424242</color>
<color name="material_grey_850">#ff303030</color>
<color name="material_grey_900">#ff212121</color>
</resources>"""
NINEPATCH_XML = """<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/dule_pic"
android:dither="true"/>"""
GRADIENT_LINEAR_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<gradient android:angle="90" android:centerColor="#FFEB82" android:endColor="#35B2DE" android:startColor="#DEACAB" />
<stroke android:dashGap="5dip" android:dashWidth="4dip" android:width="3dip" android:color="#fff" />
</shape>"""
GRADIENT_RADIAL_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dip" android:shape="ring" android:thickness="70dip" android:useLevel="false">
<gradient android:centerColor="#FFEB82" android:endColor="#35B2DE" android:gradientRadius="70"
android:startColor="#DEACAB" android:type="radial" android:useLevel="false" />
</shape>"""
GRADIENT_SWEEP_XML = """<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="8" android:shape="ring" android:thicknessRatio="3" android:useLevel="false">
<gradient android:centerColor="#FFEB82" android:endColor="#35B2DE"
android:startColor="#DEACAB" android:type="sweep" android:useLevel="false" />
</shape>"""
def pack_argb(a: int, r: int, g: int, b: int) -> int:
return ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
def case_drawable_resource_naming_and_argb_color():
pat = re.compile(r"^[a-z][a-z0-9_.]*$")
names = {
"btn_back_selector": bool(pat.match("btn_back_selector")),
"1icon": bool(pat.match("1icon")),
"BtnNormal": bool(pat.match("BtnNormal")),
"pic_9.9": bool(pat.match("pic_9.9")),
}
c_root = ET.fromstring(COLOR_DRAWABLE_XML)
res_root = ET.fromstring(COLORS_VALUES_XML)
omitted_alpha = 0xFF0000
opaque_red = pack_argb(0xFF, 0xFF, 0x00, 0x00)
actual = {
"naming_validation": names,
"color_drawable_attr": c_root.attrib[NS + "color"],
"values_color_count": len(res_root.findall("color")),
"argb_opaque_red_hex": f"0x{opaque_red:08X}",
"omitted_alpha_byte": (omitted_alpha >> 24) & 0xFF,
"argb_black_hex": f"0x{pack_argb(0xFF, 0x00, 0x00, 0x00):08X}",
}
expected = {
"naming_validation": {
"btn_back_selector": True,
"1icon": False,
"BtnNormal": False,
"pic_9.9": True,
},
"color_drawable_attr": "#FF0000",
"values_color_count": 7,
"argb_opaque_red_hex": "0xFFFF0000",
"omitted_alpha_byte": 0,
"argb_black_hex": "0xFF000000",
}
return {
"name": "drawable_resource_naming_and_argb_color",
"summary": "Verify Android drawable filename regex, ColorDrawable XML, colors.xml, and ARGB alpha packing",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_ninepatch_xml_and_bitmap_wrapper():
root = ET.fromstring(NINEPATCH_XML)
actual = {
"tag": root.tag,
"src": root.attrib[NS + "src"],
"dither": root.attrib[NS + "dither"] == "true",
"required_dir": "res/drawable",
"requires_1px_black_border_in_aapt": True,
}
expected = {
"tag": "nine-patch",
"src": "@drawable/dule_pic",
"dither": True,
"required_dir": "res/drawable",
"requires_1px_black_border_in_aapt": True,
}
return {
"name": "ninepatch_xml_and_bitmap_wrapper",
"summary": "Verify <nine-patch> XML attributes and AAPT NinePatch directory/border constraints",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_shape_and_gradient_xml_attributes():
lin = ET.fromstring(GRADIENT_LINEAR_XML)
rad = ET.fromstring(GRADIENT_RADIAL_XML)
swp = ET.fromstring(GRADIENT_SWEEP_XML)
lin_grad = lin.find("gradient")
rad_grad = rad.find("gradient")
swp_grad = swp.find("gradient")
lin_stroke = lin.find("stroke")
angle = int(lin_grad.attrib[NS + "angle"])
actual = {
"linear_shape": lin.attrib[NS + "shape"],
"linear_angle_valid_mult45": angle % 45 == 0,
"linear_stroke_dash": [lin_stroke.attrib[NS + "dashWidth"], lin_stroke.attrib[NS + "dashGap"]],
"radial_type": rad_grad.attrib[NS + "type"],
"radial_radius": int(rad_grad.attrib[NS + "gradientRadius"]),
"sweep_shape": swp.attrib[NS + "shape"],
"sweep_ratios": [int(swp.attrib[NS + "innerRadiusRatio"]), int(swp.attrib[NS + "thicknessRatio"])],
}
expected = {
"linear_shape": "oval",
"linear_angle_valid_mult45": True,
"linear_stroke_dash": ["4dip", "5dip"],
"radial_type": "radial",
"radial_radius": 70,
"sweep_shape": "ring",
"sweep_ratios": [8, 3],
}
return {
"name": "shape_and_gradient_xml_attributes",
"summary": "Verify <shape> and <gradient> XML attributes for linear, radial, and sweep gradients",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_programmatic_shape_drawable_bounds_and_path():
x, y, width, height = 10, 10, 400, 100
bounds = []
for _ in range(7):
bounds.append((x, y, x + width, y + height))
y += height + 5
diamond = [(50, 0), (0, 50), (50, 100), (100, 50)]
# Shoelace area of diamond
area = 0.5 * abs(
sum(diamond[i][0] * diamond[(i + 1) % 4][1] - diamond[(i + 1) % 4][0] * diamond[i][1] for i in range(4))
)
actual = {
"drawable_count": len(bounds),
"first_bounds": list(bounds[0]),
"last_bounds": list(bounds[-1]),
"diamond_path_area": int(area),
}
expected = {
"drawable_count": 7,
"first_bounds": [10, 10, 410, 110],
"last_bounds": [10, 640, 410, 740],
"diamond_path_area": 5000,
}
return {
"name": "programmatic_shape_drawable_bounds_and_path",
"summary": "Verify 7 programmatic ShapeDrawable vertical bounds stack and 100x100 diamond PathShape area",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_drawable_resource_naming_and_argb_color(),
case_ninepatch_xml_and_bitmap_wrapper(),
case_shape_and_gradient_xml_attributes(),
case_programmatic_shape_drawable_bounds_and_path(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 [a-z][a-z0-9_.]* 命名约束、0xFFFF0000 与漏写 Alpha 差异、三种渐变 XML 合法性及 7 个 ShapeDrawable 边界坐标。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:8703e2333d17f2e7fa8087fce039bee767ae1fd3a8fb60f3c9dcd80b1936d385
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:b68802ab37fa73d233b9b0467f3dfb419657559dc645fcf8eb9d00462c7087c2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Java 代码中写 btn.setBackgroundColor(0xFF0000) 为什么看不到红色背景?应如何修正?
展开参考解答
Java 中 32 位颜色整数按 0xAARRGGBB 解析,0xFF0000 等价于 0x00FF0000,其 Alpha 通道为 0(完全透明);必须补齐不透明通道写作 0xFFFF0000 或使用 Color.RED / Color.rgb(255, 0, 0)。