8.3.2 绘图类实战示例
通过双缓冲手绘涂鸦画板与 FrameLayout 双层图像逐像素擦除(刮刮卡式前景透底)两个实战示例,演练 Bitmap、Canvas、Path 与触摸事件的协同。
学完这一章,你能够
- 通过双缓冲手绘涂鸦画板与 FrameLayout 双层图像逐像素擦除(刮刮卡式前景透底)两个实战示例,演练 Bitmap、Canvas、Path 与触摸事件的协同。
实战示例 1:基于双缓冲的简易画图板
为巩固 `Bitmap`、`Canvas`、`Paint` 与 `Path` 的综合运用,本节实现两个交互绘图案例。第一个案例是手绘涂鸦画板:核心思路是继承自定义 `View`,并在其中引入“双缓冲”机制——在 `onMeasure()` 中按视图尺寸创建离屏 `ARGB_8888` 缓冲 `Bitmap` 与绑定该位图的内存 `Canvas`;画笔配置为 `STROKE`、抗锯齿、圆角连接(`Join.ROUND`)与圆角笔帽(`Cap.ROUND`)、线宽 `20px`;在 `onTouchEvent()` 中捕获 `ACTION_DOWN` 调用 `mPath.moveTo()`,捕获 `ACTION_MOVE` 且位移 `|dx| > 3 || |dy| > 3` 时调用 `mPath.lineTo()` 并触发 `invalidate()`;最终 `onDraw()` 先把路径绘入内存缓冲画布,再一次性将 `mBitmap` 绘制到屏幕画布,从而保留历史笔画。可在此基础上继续扩展画笔粗细、颜色切换与图片导出功能。
实战示例 2:FrameLayout 双层前景逐像素擦除
第二个案例演示“刮刮卡”式的双层图像前景擦除效果:外层选择页由 `ImageView`、确认按钮与 `Gallery`(注:`Gallery` 自 API 16 起已废弃,现代项目宜改用 `RecyclerView` 或 `ViewPager2`)组成,`MeiziAdapter` 继承 `BaseAdapter` 管理 21 组前后对照素材,主页面监听选中索引后通过 `Intent` + `Bundle` 传递 `"num"` 参数进入擦除页。
擦除页 `activity_caclothes.xml` 采用 `FrameLayout` 叠放底层目标 `ImageView`(`img_after`)与顶层前景 `ImageView`(`img_before`)。Java 类 `CaClothes` 解码两张图后,创建可变位图 `alterBitmap` 并将前景图绘制其上,为顶层 `ImageView` 注册 `OnTouchListener`;手指滑动时在嵌套循环 `for (int i = -20; i < 20; i++)` 与 `for (int j = -20; j < 20; j++)` 内做边界合法性判断,并调用 `alterBitmap.setPixel(..., Color.TRANSPARENT)` 将触点周边像素设为透明以透出底层图像。核对代码细节可知:`-20` 到 `19` 实际跨度为 `40×40 = 1600` 个像素(而非注释所述的 `20×20`),且逐像素设为透明既会在边缘留下明显的方块锯齿,又在频繁拖动时开销偏高;后续章节将改用 `PorterDuff.Mode.DST_OUT` 配合圆润 `Path` 实现平滑擦除。原示例包 `DrawDemo1.zip` 因停采限制未下载并已登记。
验证双缓冲画板触摸抖动过滤、21 项适配器传参及 40x40 像素擦除边界裁剪
展开查看收起
"""Offline verification lab for Android Ch 111: tutorial-bitmap-demo."""
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}"
SELECT_LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<ImageView android:id="@+id/img_choose" android:layout_width="320dp" android:layout_height="320dp" />
<Button android:id="@+id/btn_choose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="确认选择" />
<Gallery android:id="@+id/gay_choose" android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="25dp" android:spacing="1pt" android:unselectedAlpha="0.6" />
</LinearLayout>"""
ERASE_LAYOUT_XML = """<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView android:id="@+id/img_after" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<ImageView android:id="@+id/img_before" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</FrameLayout>"""
def case_double_buffer_sketchpad_touch_path():
# Simulate MyView onTouchEvent jitter filter: dx > 3 or dy > 3
events = [
("DOWN", 10, 10),
("MOVE", 12, 11), # dx=2, dy=1 -> filtered
("MOVE", 18, 12), # dx=6, dy=1 -> accepted
("MOVE", 19, 13), # dx=1, dy=1 -> filtered
("MOVE", 30, 40), # dx=11, dy=27 -> accepted
]
path_ops = []
last_x = last_y = 0
for act, x, y in events:
if act == "DOWN":
last_x, last_y = x, y
path_ops.append(("moveTo", x, y))
elif act == "MOVE":
if abs(x - last_x) > 3 or abs(y - last_y) > 3:
path_ops.append(("lineTo", x, y))
last_x, last_y = x, y
w, h = 480, 800
actual = {
"offscreen_bitmap_bytes": w * h * 4,
"path_ops": [list(op) for op in path_ops],
"accepted_segments": sum(1 for op in path_ops if op[0] == "lineTo"),
}
expected = {
"offscreen_bitmap_bytes": 1536000,
"path_ops": [["moveTo", 10, 10], ["lineTo", 18, 12], ["lineTo", 30, 40]],
"accepted_segments": 2,
}
return {
"name": "double_buffer_sketchpad_touch_path",
"summary": "Verify double-buffered Bitmap Canvas allocation and >3px touch jitter filter",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_gallery_adapter_and_bundle_selection():
root = ET.fromstring(SELECT_LAYOUT_XML)
ids = [c.attrib[NS + "id"] for c in root if (NS + "id") in c.attrib]
image_ids = [f"pre{i}" for i in range(1, 22)]
selected_index = 4
bundle = {"num": str(selected_index)}
parsed_pos = int(bundle["num"])
actual = {
"select_layout_ids": ids,
"adapter_count": len(image_ids),
"selected_resource": image_ids[parsed_pos],
"parsed_bundle_index": parsed_pos,
}
expected = {
"select_layout_ids": ["@+id/img_choose", "@+id/btn_choose", "@+id/gay_choose"],
"adapter_count": 21,
"selected_resource": "pre5",
"parsed_bundle_index": 4,
}
return {
"name": "gallery_adapter_and_bundle_selection",
"summary": "Verify Gallery selector layout, 21-item BaseAdapter, and Bundle index passing",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pixel_erasure_block_bounds_and_clipping():
root = ET.fromstring(ERASE_LAYOUT_XML)
layer_ids = [c.attrib[NS + "id"] for c in root]
img_w, img_h = 200, 200
def erase_count(cx: int, cy: int):
erased = 0
for i in range(-20, 20):
for j in range(-20, 20):
nx, ny = i + cx, j + cy
if 0 <= nx < img_w and 0 <= ny < img_h:
erased += 1
return erased
actual = {
"frame_layers_bottom_to_top": layer_ids,
"center_touch_erased_pixels": erase_count(100, 100),
"corner_touch_clipped_pixels": erase_count(5, 5),
"loop_span_is_40x40_not_20x20": erase_count(100, 100) == 40 * 40,
}
expected = {
"frame_layers_bottom_to_top": ["@+id/img_after", "@+id/img_before"],
"center_touch_erased_pixels": 1600,
"corner_touch_clipped_pixels": 625,
"loop_span_is_40x40_not_20x20": True,
}
return {
"name": "pixel_erasure_block_bounds_and_clipping",
"summary": "Verify FrameLayout dual-layer order and -20..19 (40x40) setPixel bounds clipping",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pixel_block_vs_smooth_path_erasure_comparison():
# Compare 40x40 square area vs radius-20 circle area
square_px = 40 * 40
circle_px = sum(1 for i in range(-20, 20) for j in range(-20, 20) if i * i + j * j <= 20 * 20)
actual = {
"square_setpixel_calls_per_move": square_px,
"circle_radius20_pixels": circle_px,
"square_has_blocky_corners": square_px > circle_px,
}
expected = {
"square_setpixel_calls_per_move": 1600,
"circle_radius20_pixels": 1255,
"square_has_blocky_corners": True,
}
return {
"name": "pixel_block_vs_smooth_path_erasure_comparison",
"summary": "Verify why 40x40 square setPixel loops create blocky edges compared to round Path erasure",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_double_buffer_sketchpad_touch_path(),
case_gallery_adapter_and_bundle_selection(),
case_pixel_erasure_block_bounds_and_clipping(),
case_pixel_block_vs_smooth_path_erasure_comparison(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
双重循环遍历的是轴对齐矩形区域(实际为 40×40 方块),边缘无抗锯齿且直接修改离散像素;更优方案是结合圆角画笔 Path 与 PorterDuff.Mode.DST_OUT 混合模式进行平滑擦除。