8.3.14 Paint几个枚举/常量值以及ShadowLayer阴影效果
核对 Android Paint 源码中 Paint.Style、Paint.Cap、Paint.Join、Paint.Align 枚举与 nativeInt 机制、FontMetrics/FontMetricsInt 字体五线测量及 setShadowLayer/clearShadowLayer 阴影层控制。
学完这一章,你能够
- 核对 Android Paint 源码中 Paint.Style、Paint.Cap、Paint.Join、Paint.Align 枚举与 nativeInt 机制、FontMetrics/FontMetricsInt 字体五线测量及 setShadowLayer/clearShadowLayer 阴影层控制。
Paint 枚举封装机制与 Style、Cap、Join 详解
`Paint` 类内部通过带整型字段 `nativeInt` 的 Java 枚举将高层配置传递给底层 JNI/Skia 引擎。以 `Paint.Style` 为例,其枚举常量 `FILL(0)`(仅填充内部,默认)、`STROKE(1)`(仅描边)与 `FILL_AND_STROKE(2)`(填充并描边)通过 `setStyle(Style)` 将 `style.nativeInt` 交给 `native_setStyle()` 生效。
控制线帽与折角外观的两个枚举分别是 `Paint.Cap` 与 `Paint.Join`:`setStrokeCap(Paint.Cap)` 控制路径首尾端点形状,支持 `BUTT(0)`(平头且不超出路径端点,默认)、`ROUND(1)`(半圆端帽,向外延展半个线宽)与 `SQUARE(2)`(方形端帽,同样向外延展半个线宽);`setStrokeJoin(Paint.Join)` 控制多段线拼接处的拐角样式,支持 `MITER(0)`(尖锐斜接,默认)、`ROUND(1)`(圆弧平滑过渡,手绘涂鸦场景最常用)与 `BEVEL(2)`(斜切平角)。当选用 `MITER` 时,还可调用 `setStrokeMiter(float miter)`(默认值 `4.0`,要求 `>= 0`)限制锐角尖刺最大长度与线宽之比 `1 / sin(θ/2)`,超出阈值时自动回退为 `BEVEL` 斜切(本站实验验证 20° 锐角触发回退而 60° 保持尖角)。
Paint.Align 文本对齐纠偏与 FontMetrics 测量体系
`setTextAlign(Paint.Align)` 决定 `canvas.drawText(text, x, y, paint)` 中文本相对基准横坐标 `x` 的对齐方式(配合 `setTextSize()` 控制字号)。需特别纠偏:Android 中 `Paint.Align.LEFT(0)` 表示文本**左边缘**对齐 `x`(即文字绘制在 `x` 的右侧 `[x, x + w]`);`Paint.Align.RIGHT(2)` 表示文本**右边缘**对齐 `x`(即文字绘制在 `x` 的左侧 `[x - w, x]`);`Paint.Align.CENTER(1)` 则以 `x` 为水平中点向两侧对称展开 `[x - w/2, x + w/2]`。参考原文把 `LEFT`/`RIGHT` 的左右绘制方向写反,编码时应以官方文档为准。
`Paint.FontMetrics`(浮点)与 `Paint.FontMetricsInt`(整型)用于精确测量字体的垂直边界,五项指标均以基线(`Baseline` 设为 `0`,向上为负、向下为正)为原点:`top` 为最高字形顶到基线的极限负距离,`ascent` 为常规单行字符顶到基线的负距离,`descent` 为常规字符底到基线的正距离,`bottom` 为最低字形底到基线的极限正距离,`leading` 为上一行 `descent` 与下一行 `ascent` 之间的推荐行距。自定义控件实现文字垂直居中于 `centerY` 时,可利用 `baseline = centerY - (fm.ascent + fm.descent) / 2f` 精确求解(本站实验针对 `[-64, -56, 15, 17, 0]` 核算居中于 `200` 的基线为 `220.5`)。
ShadowLayer 阴影层设置与清除
除在 `TextView` XML 中声明文字阴影外,`Paint` 提供了通用的 `setShadowLayer(float radius, float dx, float dy, int shadowColor)` 方法为绘制内容添加投影,调用 `clearShadowLayer()` 即可清除。需精准说明参数含义:`radius` 为高斯模糊半径(像素,并非“阴影角度”,设为 `0` 时关闭阴影层),`dx`/`dy` 为阴影在 X/Y 轴方向的偏移量,`shadowColor` 为包含 Alpha 通道的阴影色值。在 Android 9(API 28)之前,`setShadowLayer` 对非文字的几何图形与位图需关闭单视图硬件加速(`LAYER_TYPE_SOFTWARE`)方可完整生效,API 28 起硬件管线已原生支持。遇到参数疑问时对照官方文档与源码动手验证是最稳妥的学习路径。
运行离线 Paint 枚举 nativeInt、Cap/Miter 几何、Align/FontMetrics 基线与 ShadowLayer 核验
展开查看收起
"""Offline Android graphics verifier for Ch 123: Paint Enums, FontMetrics & ShadowLayer."""
from dataclasses import dataclass
import json
import math
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
@dataclass
class ShadowState:
radius: float = 0.0
dx: float = 0.0
dy: float = 0.0
color: int = 0
@property
def active(self) -> bool:
return self.radius > 0.0 and ((self.color >> 24) & 0xFF) > 0
def clear(self) -> None:
self.radius = 0.0
self.dx = 0.0
self.dy = 0.0
self.color = 0
def text_x_span(anchor_x: float, text_width: float, align: str) -> list[float]:
if align == "LEFT":
return [anchor_x, anchor_x + text_width]
if align == "CENTER":
return [anchor_x - text_width / 2.0, anchor_x + text_width / 2.0]
if align == "RIGHT":
return [anchor_x - text_width, anchor_x]
raise ValueError(align)
def cap_extension(stroke_width: float, cap: str) -> float:
if cap == "BUTT":
return 0.0
if cap in ("ROUND", "SQUARE"):
return stroke_width / 2.0
raise ValueError(cap)
def miter_falls_back_to_bevel(angle_deg: float, miter_limit: float) -> bool:
ratio = 1.0 / math.sin(math.radians(angle_deg / 2.0))
return ratio > miter_limit
def main() -> None:
# Case 1: Paint.Style / Cap / Join / Align nativeInt enums matching Android Paint.java
c1_actual = {
"Style": {"FILL": 0, "STROKE": 1, "FILL_AND_STROKE": 2},
"Cap": {"BUTT": 0, "ROUND": 1, "SQUARE": 2},
"Join": {"MITER": 0, "ROUND": 1, "BEVEL": 2},
"Align": {"LEFT": 0, "CENTER": 1, "RIGHT": 2},
}
c1_expected = {
"Style": {"FILL": 0, "STROKE": 1, "FILL_AND_STROKE": 2},
"Cap": {"BUTT": 0, "ROUND": 1, "SQUARE": 2},
"Join": {"MITER": 0, "ROUND": 1, "BEVEL": 2},
"Align": {"LEFT": 0, "CENTER": 1, "RIGHT": 2},
}
# Case 2: Stroke Cap endpoint extension & Join miter limit (default 4.0)
c2_actual = {
"cap_ext_w20": {cap: cap_extension(20.0, cap) for cap in ("BUTT", "ROUND", "SQUARE")},
"miter_fallback_deg20_limit4": miter_falls_back_to_bevel(20.0, 4.0),
"miter_fallback_deg60_limit4": miter_falls_back_to_bevel(60.0, 4.0),
}
c2_expected = {
"cap_ext_w20": {"BUTT": 0.0, "ROUND": 10.0, "SQUARE": 10.0},
"miter_fallback_deg20_limit4": True,
"miter_fallback_deg60_limit4": False,
}
# Case 3: Paint.Align horizontal bounds around x=400 (text_width=120) & FontMetricsInt baseline centering
fm = {"top": -64, "ascent": -56, "descent": 15, "bottom": 17, "leading": 0}
center_y = 200.0
baseline_for_center = center_y - (fm["ascent"] + fm["descent"]) / 2.0
c3_actual = {
"align_spans_x400_w120": {a: text_x_span(400.0, 120.0, a) for a in ("LEFT", "CENTER", "RIGHT")},
"metrics_ordered": fm["top"] <= fm["ascent"] < 0 < fm["descent"] <= fm["bottom"],
"line_height_top_to_bottom": fm["bottom"] - fm["top"],
"vertical_center_baseline_at_y200": baseline_for_center,
}
c3_expected = {
"align_spans_x400_w120": {
"LEFT": [400.0, 520.0],
"CENTER": [340.0, 460.0],
"RIGHT": [280.0, 400.0],
},
"metrics_ordered": True,
"line_height_top_to_bottom": 81,
"vertical_center_baseline_at_y200": 220.5,
}
# Case 4: setShadowLayer(5, 0, 0, Color.BLACK) & clearShadowLayer()
sh = ShadowState(radius=5.0, dx=0.0, dy=0.0, color=0xFF000000)
active_before = sh.active
shadow_offset_box = [400.0 + sh.dx - sh.radius, 400.0 + sh.dy - sh.radius, 400.0 + sh.dx + sh.radius]
sh.clear()
c4_actual = {
"active_after_set": active_before,
"blur_radius": 5.0,
"shadow_halo_sample": shadow_offset_box,
"active_after_clear": sh.active,
}
c4_expected = {
"active_after_set": True,
"blur_radius": 5.0,
"shadow_halo_sample": [395.0, 395.0, 405.0],
"active_after_clear": False,
}
cases = [
{
"name": "paint_enum_native_values",
"summary": "核验 Paint.Style、Paint.Cap、Paint.Join 与 Paint.Align 四组枚举的 nativeInt 映射值",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "stroke_cap_extension_and_miter_limit",
"summary": "核验 BUTT/ROUND/SQUARE 端点延展量及 setStrokeMiter(4.0) 在锐角 20°/60° 下的倒角回退判定",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "text_align_and_fontmetrics_baseline",
"summary": "核验 Paint.Align 相对基准点 x 的真实对齐区间及 FontMetricsInt 五值顺序与垂直居中基线求解",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "shadow_layer_set_and_clear",
"summary": "核验 setShadowLayer(5, 0, 0, Color.BLACK) 的激活条件、模糊半径与 clearShadowLayer() 清除行为",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
实际占据 `[400, 520]`:`Paint.Align.LEFT` 表示文本左边缘与起始横坐标 `x` 对齐,文本向 `x` 的右侧绘制。