8.2.1 Bitmap(位图)全解析 Part 1
厘清 Drawable、Bitmap、Canvas 与 Matrix 的职责分工,系统解析 BitmapFactory、Options 参数、位图获取、裁剪缩放及 DecorView 应用内截屏。
学完这一章,你能够
- 厘清 Drawable、Bitmap、Canvas 与 Matrix 的职责分工,系统解析 BitmapFactory、Options 参数、位图获取、裁剪缩放及 DecorView 应用内截屏。
android.graphics 四大核心类与 Bitmap 创建机制
在 `android.graphics` 底层图形体系中,四个核心概念各司其职:`Drawable` 是通用的可绘制图形包装(类比画框,可承载位图或 XML 矢量/状态图形);`Bitmap` 表示内存中的像素位图(类比画架上的画纸,支持读取宽高与像素、裁剪、缩放及压缩导出);`Canvas` 是执行绘制指令的画布,配合 `Paint` 与 `Path` 渲染几何图形与文字;`Matrix` 则用于几何仿射变换(平移、缩放、旋转、错切)与颜色矩阵特效。
阅读源码可见 `Bitmap` 的构造方法为包级/私有,应用层不能直接 `new Bitmap()`,底层需经 JNI 分配像素缓冲区,统一通过工厂类 `BitmapFactory` 的 `decodeXxx()` 静态方法或 `Bitmap.createBitmap()` 系列方法创建。每个 `decodeXxx()` 重载都可传入静态内部类 `BitmapFactory.Options`,用于控制解码采样率、颜色配置以及仅读取尺寸不分配像素的 `inJustDecodeBounds` 选项。
Bitmap 常用方法与 BitmapFactory.Options 核心参数
`Bitmap` 常用实例方法包括:`compress(format, quality, stream)` 将位图按 PNG/JPEG/WEBP 压缩写入输出流(`quality` 取 `0–100`,PNG 为无损格式会忽略品质值);`recycle()` 与 `isRecycled()` 显式标记回收与查询状态;`getWidth()`/`getHeight()` 获取像素尺寸;`isMutable()` 判断像素是否可修改;`getScaledWidth(Canvas)`/`getScaledHeight(Canvas)` 获取按画布密度缩放后的尺寸。常用静态创建方法涵盖复制、按宽高与 `Config` 新建空白位图、按 `(x, y, width, height)` 区域裁剪以及附带 `Matrix` 变换的 `createBitmap()` 和 `createScaledBitmap()`。
`BitmapFactory.Options` 最常用的配置字段为:`inJustDecodeBounds`(设为 `true` 时只解析边界尺寸写入 `outWidth`/`outHeight`,不分配像素内存);`inSampleSize`(降采样倍数,设为 `4` 时宽高各缩至 `1/4`、总像素与内存降至 `1/16`);`inDensity`、`inTargetDensity` 与 `inScaled`(控制从源资源密度到目标屏幕密度的自动缩放比例)。
位图加载、区域裁剪、缩放与应用内截屏实战
加载位图主要有两种途径:一是由输入流或资源构建 `BitmapDrawable` 再调用 `getBitmap()`;二是直接调用 `BitmapFactory` 的 `decodeResource`、`decodeFile`、`decodeByteArray`(需先判空数组长度)或 `decodeStream`。拿到 `Bitmap` 对象后即可通过 `getByteCount()`(API 19+ 复用场景可用 `getAllocationByteCount()`)、`getWidth()`、`getHeight()` 检查元信息。
日常处理中,裁剪局部区域只需调用 `Bitmap.createBitmap(src, x, y, width, height)`(须满足 `x + width <= src.getWidth()` 且 `y + height <= src.getHeight()`);等比或指定尺寸缩放可调用 `Bitmap.createScaledBitmap(src, dstW, dstH, filter)`。若要实现应用内截屏,可通过 `getWindow().getDecorView()` 取得窗口根视图,创建与根视图等宽高的空白 `Bitmap`(示例中用 `ARGB_4444`,现代 Android 推荐 `ARGB_8888`),调用 `contentView.draw(new Canvas(bitmap))` 将视图树渲染进位图,再经 `compress(PNG, 100, fos)` 保存到文件(该方法仅截取当前应用窗口内容)。本站离线实验核验了四种像素格式内存占用、密度缩放、裁剪越界检测与截屏生命周期。
验证 Bitmap 像素格式内存计算、密度缩放、裁剪越界保护与 DecorView 截屏参数
"""Offline verification lab for Android Ch 108: tutorial-bitmap1."""
import json
VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"
def case_bitmap_config_memory_and_density_scaling():
w, h = 1080, 1920
bpp = {"ARGB_8888": 4, "RGB_565": 2, "ARGB_4444": 2, "ALPHA_8": 1}
mem_bytes = {k: w * h * v for k, v in bpp.items()}
# inDensity=320 (xhdpi) -> inTargetDensity=480 (xxhdpi)
in_density, target_density = 320, 480
scaled_w = round(200 * target_density / in_density)
scaled_h = round(100 * target_density / in_density)
actual = {
"byte_counts_1080x1920": mem_bytes,
"density_scaled_dims": [scaled_w, scaled_h],
"insamplesize_4_area_ratio": 1.0 / (4 * 4),
}
expected = {
"byte_counts_1080x1920": {
"ARGB_8888": 8294400,
"RGB_565": 4147200,
"ARGB_4444": 4147200,
"ALPHA_8": 2073600,
},
"density_scaled_dims": [300, 150],
"insamplesize_4_area_ratio": 0.0625,
}
return {
"name": "bitmap_config_memory_and_density_scaling",
"summary": "Verify ARGB_8888/RGB_565/ARGB_4444/ALPHA_8 byte counts and inDensity->inTargetDensity scaling",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bitmap_drawable_and_factory_decode_paths():
def bytes_to_bitmap(buf: bytes):
if len(buf) == 0:
return None
return {"decoded_bytes": len(buf)}
actual = {
"factory_methods": ["decodeResource", "decodeFile", "decodeByteArray", "decodeStream"],
"empty_bytes_returns_null": bytes_to_bitmap(b"") is None,
"nonempty_bytes_decoded": bytes_to_bitmap(b"\x89PNG\r\n\x1a\n"),
"private_constructor_jni_created": True,
}
expected = {
"factory_methods": ["decodeResource", "decodeFile", "decodeByteArray", "decodeStream"],
"empty_bytes_returns_null": True,
"nonempty_bytes_decoded": {"decoded_bytes": 8},
"private_constructor_jni_created": True,
}
return {
"name": "bitmap_drawable_and_factory_decode_paths",
"summary": "Verify BitmapFactory decode entrypoints and empty byte-array guard",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bitmap_crop_and_scale_bounds():
src_w, src_h = 600, 800
crop_x, crop_y, crop_w, crop_h = 100, 100, 200, 200
crop_valid = (crop_x >= 0 and crop_y >= 0 and crop_x + crop_w <= src_w and crop_y + crop_h <= src_h)
invalid_crop = (500 + 200 <= src_w)
scaled_w, scaled_h = 300, 400
actual = {
"crop_valid": crop_valid,
"crop_rect": [crop_x, crop_y, crop_x + crop_w, crop_y + crop_h],
"out_of_bounds_crop_rejected": not invalid_crop,
"scaled_dims": [scaled_w, scaled_h],
"aspect_preserved": (scaled_w * src_h) == (scaled_h * src_w),
}
expected = {
"crop_valid": True,
"crop_rect": [100, 100, 300, 300],
"out_of_bounds_crop_rejected": True,
"scaled_dims": [300, 400],
"aspect_preserved": True,
}
return {
"name": "bitmap_crop_and_scale_bounds",
"summary": "Verify createBitmap(src, 100, 100, 200, 200) crop bounds and createScaledBitmap dimensions",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_decorview_screenshot_and_compress_contract():
decor_w, decor_h = 720, 1280
recycled = False
is_recycled_before = recycled
recycled = True
is_recycled_after = recycled
actual = {
"screenshot_argb4444_bytes": decor_w * decor_h * 2,
"screenshot_argb8888_bytes": decor_w * decor_h * 4,
"png_ignores_quality_setting": True,
"jpeg_quality_range": [0, 100],
"recycled_transition": [is_recycled_before, is_recycled_after],
}
expected = {
"screenshot_argb4444_bytes": 1843200,
"screenshot_argb8888_bytes": 3686400,
"png_ignores_quality_setting": True,
"jpeg_quality_range": [0, 100],
"recycled_transition": [False, True],
}
return {
"name": "decorview_screenshot_and_compress_contract",
"summary": "Verify DecorView screenshot Bitmap sizing, PNG/JPEG compress quality rules, and recycle state",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_bitmap_config_memory_and_density_scaling(),
case_bitmap_drawable_and_factory_decode_paths(),
case_bitmap_crop_and_scale_bounds(),
case_decorview_screenshot_and_compress_contract(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 1080x1920 下 ARGB_8888(8.29MB)/RGB_565(4.15MB) 字节数、320->480 dpi 缩放、裁剪范围校验及 PNG 无损压缩契约。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:05f21ebd795f3117f079d2c47e0b1437cab31c7794e1bd0a48121e25870f5668
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:90aed459a3a7945db96b19d1307a300b47a907e5e84e611453ca1cae801b137a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
将 BitmapFactory.Options.inSampleSize 设为 4 后,解码得到的 Bitmap 占用的像素内存大约是原图的几分之几?
展开参考解答
inSampleSize=4 会将位图的宽度和高度同时缩为原来的 1/4,因此总像素数与内存占用降至原来的 1/(4×4) = 1/16。