8.3.1 三个绘图工具类详解
系统梳理 Android 自定义绘制三大基石 Paint(画笔)、Canvas(画布)与 Path(路径)的核心 API,并通过自定义 View 演练基础图元、路径文字与表盘旋转绘制。
学完这一章,你能够
- 系统梳理 Android 自定义绘制三大基石 Paint(画笔)、Canvas(画布)与 Path(路径)的核心 API,并通过自定义 View 演练基础图元、路径文字与表盘旋转绘制。
Paint 画笔属性与文本测量 API
自定义 `View` 绘制建立在 `android.graphics` 的三个核心类之上:`Paint`(画笔)、`Canvas`(画布)与 `Path`(路径)。`Paint` 控制渲染风格,图形绘制相关方法涵盖颜色与透明度(`setARGB`、`setAlpha`、`setColor`)、画质与滤镜(`setAntiAlias`、`setDither`、`setFilterBitmap`、`setMaskFilter`、`setColorFilter`、`setPathEffect`、`setShader`、`setShadowLayer`、`clearShadowLayer`)以及描边与填充样式(`setStyle` 取 `FILL`/`STROKE`/`FILL_AND_STROKE`,配合 `setStrokeWidth`、`setStrokeCap`、`setStrokeJoin`、`setStrokeMiter` 与重叠混合 `setXfermode`)。
文本排版相关方法则包括字号与对齐(`setTextSize`、`setTextAlign`、`setTypeface`)、拉伸与倾斜(`setTextScaleX`、`setTextSkewX`)、修饰效果(`setFakeBoldText`、`setSubpixelText`、`setUnderlineText`、`setStrikeThruText`)以及字形度量工具:`ascent()` 与 `descent()` 分别返回基线(baseline)之上到最高点与之下到最低点的距离,`breakText()` 用于测算指定最大宽度内一行能容纳的字符数。
Canvas 画布绘制、裁剪与坐标变换栈
`Canvas` 可通过无参构造配合 `setBitmap()` 或直接以非空 `Bitmap` 构造,其 `drawXXX()` 方法族按调用顺序逐层叠加渲染,包括 `drawRect`、`drawPath`、`drawBitmap(bitmap, src, dst, paint)`(源/目标区域不一致时会发生拉伸缩放)、`drawLine`、`drawPoint`、`drawText`、`drawOval`、`drawCircle` 与 `drawArc(oval, startAngle, sweepAngle, useCenter, paint)`(`useCenter=true` 连结圆心构成扇形,`false` 仅绘弧/弓形)。
除直接绘制外,`Canvas` 还提供 `clipXXX()` 裁剪当前可绘区域,以及 `translate(dx, dy)`、`scale(sx, sy)`、`rotate(degrees)` 等坐标系变换。变换操作前应调用 `save()` 压栈保存画布矩阵与裁剪状态,绘制完毕调用 `restore()` 弹栈复原以防影响后续绘制;`restore()` 次数绝不能超过 `save()`,否则抛出栈下溢异常。
Path 路径构造与自定义 View 绘图实战
`Path` 用于记录任意直线、几何轮廓与曲线路径并交由 `canvas.drawPath()` 渲染。既可用 `addArc`、`addCircle`、`addOval`、`addRect`、`addRoundRect` 批量添加标准图形并配合 `isEmpty()`、`transform(Matrix)` 操作,也可用 `moveTo`(仅移动落笔点不绘制)、`lineTo`(连直线)、`quadTo`(二阶贝塞尔曲线)、`cubicTo`/`rCubicTo`(三阶绝对/相对贝塞尔曲线)与 `arcTo`(截取椭圆弧)精细描点连线。
在自定义 `MyView` 的 `onDraw(Canvas)` 中依次实践 10 个核心场景:设置画布背景色 `drawColor`、实心圆、矩形、贴图 `Bitmap`、`useCenter` 为 `true`/`false` 的弧形对比、圆角矩形、椭圆、`moveTo`/`lineTo`/`close` 闭合多边形、`drawText` 与沿路径排布的 `drawTextOnPath`,以及综合运用 `translate`、`save`/`restore`、`addArc` 与循环 `rotate(360/60)` 绘制 60 刻度(12 主刻度)的表盘与指针。本站离线实验对 Paint 度量、扇形/弓形面积、三阶贝塞尔中点、Canvas 状态栈下溢检测及 60 刻度表盘旋转角进行了精确核算。
验证 Paint 文本度量、Canvas 图元/弧形几何、Path 贝塞尔曲线与 60 刻度表盘变换栈
"""Offline verification lab for Android Ch 110: tutorial-drawable-tool."""
import json
import math
VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"
def case_paint_configuration_and_text_metrics():
paint = {
"antiAlias": True,
"style": "FILL",
"textSize_px": 36.0,
"strokeWidth_px": 5.0,
"strokeCap": "ROUND",
"strokeJoin": "MITER",
}
# Simulate breakText with monospace 18px per char against maxWidth=100px
text = "AndroidCanvas"
char_w = 18.0
max_w = 100.0
fit_count = min(len(text), int(max_w // char_w))
ascent, descent = -30.5, 8.5
line_height = round(descent - ascent, 2)
actual = {
"paint_style": paint["style"],
"textSize_px": paint["textSize_px"],
"breakText_fit_count": fit_count,
"measured_width_px": fit_count * char_w,
"font_line_height_px": line_height,
}
expected = {
"paint_style": "FILL",
"textSize_px": 36.0,
"breakText_fit_count": 5,
"measured_width_px": 90.0,
"font_line_height_px": 39.0,
}
return {
"name": "paint_configuration_and_text_metrics",
"summary": "Verify Paint configuration properties, baseline ascent/descent height, and breakText fit",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_canvas_primitives_and_arc_geometry():
# Circle (200,200,r=100), Rect (0,0,200,100), Arc in RectF(0,0,100,100) r=50 sweep=90deg
r = 50.0
sector_area = round(0.25 * math.pi * r * r, 3) # useCenter=True
chord_segment_area = round(sector_area - 0.5 * r * r, 3) # useCenter=False
round_rect_bounds = [10, 10, 210, 110]
oval_bounds = [0, 0, 200, 300]
actual = {
"circle_bbox": [100, 100, 300, 300],
"rect_area": 200 * 100,
"arc_useCenter_true_area": sector_area,
"arc_useCenter_false_area": chord_segment_area,
"round_rect_wh": [round_rect_bounds[2] - round_rect_bounds[0], round_rect_bounds[3] - round_rect_bounds[1]],
"oval_wh": [oval_bounds[2] - oval_bounds[0], oval_bounds[3] - oval_bounds[1]],
}
expected = {
"circle_bbox": [100, 100, 300, 300],
"rect_area": 20000,
"arc_useCenter_true_area": 1963.495,
"arc_useCenter_false_area": 713.495,
"round_rect_wh": [200, 100],
"oval_wh": [200, 300],
}
return {
"name": "canvas_primitives_and_arc_geometry",
"summary": "Verify Canvas drawCircle/drawRect/drawRoundRect/drawOval and drawArc useCenter geometry",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_path_polygon_bezier_and_text_on_path():
poly = [(10, 10), (100, 50), (200, 40), (300, 20), (200, 10), (100, 70), (50, 40)]
xs = [p[0] for p in poly]
ys = [p[1] for p in poly]
# Cubic Bezier from P0=(100,500), P1=(100,500), P2=(300,100), P3=(600,500) at t=0.5
p0, p1, p2, p3 = (100, 500), (100, 500), (300, 100), (600, 500)
t = 0.5
bx = (1 - t) ** 3 * p0[0] + 3 * (1 - t) ** 2 * t * p1[0] + 3 * (1 - t) * t ** 2 * p2[0] + t ** 3 * p3[0]
by = (1 - t) ** 3 * p0[1] + 3 * (1 - t) ** 2 * t * p1[1] + 3 * (1 - t) * t ** 2 * p2[1] + t ** 3 * p3[1]
# Text path diagonal (50,50)->(300,300)
diag_len = round(math.hypot(300 - 50, 300 - 50), 3)
actual = {
"polygon_vertices": len(poly),
"polygon_bbox": [min(xs), min(ys), max(xs), max(ys)],
"cubic_midpoint": [bx, by],
"text_path_diag_length": diag_len,
}
expected = {
"polygon_vertices": 7,
"polygon_bbox": [10, 10, 300, 70],
"cubic_midpoint": [237.5, 350.0],
"text_path_diag_length": 353.553,
}
return {
"name": "path_polygon_bezier_and_text_on_path",
"summary": "Verify Path polygon bounding box, cubicTo Bezier midpoint, and drawTextOnPath length",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_canvas_save_restore_stack_and_dial_ticks():
stack = [(0.0, 0.0, 0.0)] # (tx, ty, deg)
# Translate to center (150, 200)
stack[-1] = (150.0, 200.0, 0.0)
# save(), translate(-75, -75), restore()
stack.append(stack[-1])
tx, ty, deg = stack[-1]
stack[-1] = (tx - 75.0, ty - 75.0, deg)
saved_state = stack[-1]
stack.pop()
restored_state = stack[-1]
# Restore underflow check
underflow_raises = False
try:
stack.pop()
if not stack:
raise RuntimeError("Canvas restore underflow")
except RuntimeError:
underflow_raises = True
count = 60
step_deg = 360 / count
major_ticks = [i for i in range(count) if i % 5 == 0]
actual = {
"saved_inner_origin": list(saved_state[:2]),
"restored_origin": list(restored_state[:2]),
"underflow_detected": underflow_raises,
"dial_tick_count": count,
"dial_step_degrees": step_deg,
"major_tick_count": len(major_ticks),
"major_labels": [i // 5 + 1 for i in major_ticks],
}
expected = {
"saved_inner_origin": [75.0, 125.0],
"restored_origin": [150.0, 200.0],
"underflow_detected": True,
"dial_tick_count": 60,
"dial_step_degrees": 6.0,
"major_tick_count": 12,
"major_labels": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
}
return {
"name": "canvas_save_restore_stack_and_dial_ticks",
"summary": "Verify Canvas save/restore transform stack, underflow guard, and 60-tick dial rotation math",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_paint_configuration_and_text_metrics(),
case_canvas_primitives_and_arc_geometry(),
case_path_polygon_bezier_and_text_on_path(),
case_canvas_save_restore_stack_and_dial_ticks(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 breakText 截断字数、useCenter 扇形(1963.5)与弓形(713.5)面积差、cubicTo 中点 (237.5,350.0) 及 save/restore 栈与 6° 表盘步进。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:009ae2cf6e77f329d807ea15e00b76f4894a6f762a116a7f84371aa8e95a4f56
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:9ba3ab3ad90139053df569d54d37381ad55061035737d4b31d59bb3a13c18212
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Canvas 中调用 drawArc(..., useCenter, paint) 时,将 useCenter 设为 true 与 false 在填充模式下有何区别?
展开参考解答
useCenter 为 true 时弧线两端会连向椭圆中心构成封闭扇形;为 false 时仅连接弧线起止两点形成弓形区域(描边模式下则仅绘制开放弧线)。