8.1.2 Android 中的 13 种 Drawable 小结 Part 2
详解 BitmapDrawable、InsetDrawable、ClipDrawable、RotateDrawable 与 AnimationDrawable 的 XML 配置、Java 控制及 0–10000 level 驱动机制。
学完这一章,你能够
- 详解 BitmapDrawable、InsetDrawable、ClipDrawable、RotateDrawable 与 AnimationDrawable 的 XML 配置、Java 控制及 0–10000 level 驱动机制。
BitmapDrawable 与 InsetDrawable
继续梳理 Android 13 种 `Drawable` 中的接下来五类。`BitmapDrawable` 以 `<bitmap>` 为根节点对位图进行封装,支持配置 `src`、`antialias`(抗锯齿)、`filter`(缩放滤波平滑)、`dither`(颜色抖动)、`gravity`(位图小于容器时的对齐位置)及 `tileMode`(平铺模式:`disabled` 拉伸、`clamp` 边缘延伸、`repeat` 重复平铺、`mirror` 镜像平铺)。需注意一旦启用非 `disabled` 的 `tileMode`,`gravity` 属性将被忽略;Java 中可通过 `setDither(true)` 与 `setTileModeXY(TileMode.MIRROR, TileMode.MIRROR)` 实现等价效果。
`InsetDrawable`(根节点 `<inset>`)用于在另一个 Drawable 外部四周留出内缩边距,属性包含 `drawable`(若省略须内嵌一个 Drawable 子节点)、`visible` 以及 `insetLeft`/`insetRight`/`insetTop`/`insetBottom`(注意标准拼写为 `insetBottom`)。它不同于 `padding`(内容与背景边界的距离),而是直接缩小背景自身相对容器的绘制矩形,非常适合给自定义 `Dialog` 窗口增加与屏幕边缘的留白间距。
level 驱动的 ClipDrawable 与 RotateDrawable
`ClipDrawable`(根节点 `<clip>`)按 `level`(取值范围 `0–10000`)动态裁剪所包装的 Drawable,Android 系统进度条即以此实现。关键属性为 `clipOrientation`(`horizontal` 或 `vertical`)、`gravity`(裁剪起始锚点如 `left`)与 `drawable`。使用时若绑定到 `ImageView` 并计划调用 `img.getDrawable()` 强转为 `ClipDrawable`,布局中必须配置 `android:src` 而非 `android:background`(否则 `getDrawable()` 返回 `null` 触发空指针)。示例中通过 `Timer` 每 300ms 经 `Handler` 将 `level` 递增 `500`,20 步从 `0` 展露至 `10000`。
`RotateDrawable`(根节点 `<rotate>`)同样由 `0–10000` 的 `level` 线性插值驱动旋转角度,属性包括 `fromDegrees`(默认 `0`)、`toDegrees`(默认 `360`)、`pivotX`/`pivotY`(旋转中心,默认 `50%`,若旋转后边角被裁可调整锚点或边距)、`drawable` 与 `visible`。当 `fromDegrees="-180"` 且默认 `toDegrees="360"` 时,每步 `level += 400` 共 25 步即可从 `-180°` 平滑旋转至 `360°`。
帧动画载体 AnimationDrawable
`AnimationDrawable`(根节点 `<animation-list>`)用于按顺序逐帧播放一系列 Drawable,适合下拉刷新图标等无需精细交互控制的帧动画。根节点 `android:oneshot="false"` 表示循环播放(`true` 则只播一次),每个 `<item>` 指定帧图像 `drawable` 与停留毫秒数 `duration`。由于在 `Activity.onCreate()` 阶段视图尚未附着到窗口,直接调用 `ad.start()` 往往不生效,通常需借助 `Handler.postDelayed()`、`View.post()` 或 `onWindowFocusChanged()` 延迟触发播放。本站离线实验已解析全部五类 XML 并验证内缩矩形、裁剪步进、角度插值与 6 帧 600ms 周期。
验证 Bitmap/Inset/Clip/Rotate/Animation 五类 Drawable XML 属性与 level 步进计算
展开查看收起
"""Offline verification lab for Android Ch 106: tutorial-drawable2."""
import json
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}"
BITMAP_XML = """<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:dither="true"
android:src="@drawable/ic_launcher"
android:tileMode="mirror" />"""
INSET_XML = """<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/test1"
android:insetBottom="10dp"
android:insetLeft="10dp"
android:insetRight="10dp"
android:insetTop="10dp" />"""
CLIP_XML = """<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="horizontal"
android:drawable="@mipmap/ic_bg_demo"
android:gravity="left" />"""
ROTATE_XML = """<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@mipmap/ic_launcher"
android:fromDegrees="-180"
android:pivotX="50%"
android:pivotY="50%" />"""
ANIM_XML = """<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@mipmap/ic_pull_to_refresh_loading01" android:duration="100" />
<item android:drawable="@mipmap/ic_pull_to_refresh_loading02" android:duration="100" />
<item android:drawable="@mipmap/ic_pull_to_refresh_loading03" android:duration="100" />
<item android:drawable="@mipmap/ic_pull_to_refresh_loading04" android:duration="100" />
<item android:drawable="@mipmap/ic_pull_to_refresh_loading05" android:duration="100" />
<item android:drawable="@mipmap/ic_pull_to_refresh_loading06" android:duration="100" />
</animation-list>"""
def case_bitmap_drawable_xml_and_tilemode():
root = ET.fromstring(BITMAP_XML)
valid_modes = {"disabled", "clamp", "repeat", "mirror"}
tm = root.attrib[NS + "tileMode"]
actual = {
"tag": root.tag,
"dither": root.attrib[NS + "dither"] == "true",
"tileMode": tm,
"tileMode_valid": tm in valid_modes,
"gravity_ignored_when_tileMode_set": tm != "disabled",
}
expected = {
"tag": "bitmap",
"dither": True,
"tileMode": "mirror",
"tileMode_valid": True,
"gravity_ignored_when_tileMode_set": True,
}
return {
"name": "bitmap_drawable_xml_and_tilemode",
"summary": "Verify <bitmap> XML attributes and tileMode gravity override behavior",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_inset_drawable_bounds_calculation():
root = ET.fromstring(INSET_XML)
left = int(root.attrib[NS + "insetLeft"].replace("dp", ""))
top = int(root.attrib[NS + "insetTop"].replace("dp", ""))
right = int(root.attrib[NS + "insetRight"].replace("dp", ""))
bottom = int(root.attrib[NS + "insetBottom"].replace("dp", ""))
outer = (0, 0, 200, 120)
inner = (outer[0] + left, outer[1] + top, outer[2] - right, outer[3] - bottom)
actual = {
"tag": root.tag,
"insets_dp": [left, top, right, bottom],
"inner_bounds": list(inner),
}
expected = {
"tag": "inset",
"insets_dp": [10, 10, 10, 10],
"inner_bounds": [10, 10, 190, 110],
}
return {
"name": "inset_drawable_bounds_calculation",
"summary": "Verify <inset> XML attributes and inner drawable rectangle calculation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_clip_drawable_level_progression():
root = ET.fromstring(CLIP_XML)
level = 0
steps = 0
while level < 10000:
level += 500
steps += 1
full_width = 400
clipped_widths = [full_width * lv // 10000 for lv in (0, 2500, 5000, 10000)]
actual = {
"orientation": root.attrib[NS + "clipOrientation"],
"gravity": root.attrib[NS + "gravity"],
"steps_to_10000": steps,
"clipped_widths": clipped_widths,
"imageview_requires_src_for_getDrawable": True,
}
expected = {
"orientation": "horizontal",
"gravity": "left",
"steps_to_10000": 20,
"clipped_widths": [0, 100, 200, 400],
"imageview_requires_src_for_getDrawable": True,
}
return {
"name": "clip_drawable_level_progression",
"summary": "Verify <clip> XML orientation/gravity and 0..10000 level clipping progression",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_rotate_drawable_angle_interpolation():
root = ET.fromstring(ROTATE_XML)
from_deg = float(root.attrib[NS + "fromDegrees"])
to_deg = float(root.attrib.get(NS + "toDegrees", "360"))
angles = [round(from_deg + (to_deg - from_deg) * (lv / 10000.0), 2) for lv in (0, 2500, 5000, 10000)]
steps = 10000 // 400
actual = {
"fromDegrees": from_deg,
"default_toDegrees": to_deg,
"pivot": [root.attrib[NS + "pivotX"], root.attrib[NS + "pivotY"]],
"angles_at_levels": angles,
"steps_at_400_increment": steps,
}
expected = {
"fromDegrees": -180.0,
"default_toDegrees": 360.0,
"pivot": ["50%", "50%"],
"angles_at_levels": [-180.0, -45.0, 90.0, 360.0],
"steps_at_400_increment": 25,
}
return {
"name": "rotate_drawable_angle_interpolation",
"summary": "Verify <rotate> XML pivot/degrees and linear level-to-angle interpolation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_animation_drawable_frame_schedule():
root = ET.fromstring(ANIM_XML)
items = root.findall("item")
durations = [int(it.attrib[NS + "duration"]) for it in items]
actual = {
"oneshot": root.attrib[NS + "oneshot"] == "true",
"frame_count": len(items),
"cycle_duration_ms": sum(durations),
"loop_enabled": root.attrib[NS + "oneshot"] == "false",
}
expected = {
"oneshot": False,
"frame_count": 6,
"cycle_duration_ms": 600,
"loop_enabled": True,
}
return {
"name": "animation_drawable_frame_schedule",
"summary": "Verify <animation-list> oneshot flag, frame count, and 600ms total cycle duration",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_bitmap_drawable_xml_and_tilemode(),
case_inset_drawable_bounds_calculation(),
case_clip_drawable_level_progression(),
case_rotate_drawable_angle_interpolation(),
case_animation_drawable_frame_schedule(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
ImageView.getDrawable() 读取的是 android:src 对应的前景图像对象,而 android:background 需通过 View.getBackground() 获取;若仅设了 background,getDrawable() 返回 null。