蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

8.3.13 Paint API之—— Shader(图像渲染)

核对 Android Paint.setShader 的五大 Shader 子类(BitmapShader、ComposeShader、LinearGradient、RadialGradient、SweepGradient)与 TileMode(CLAMP、REPEAT、MIRROR)边界采样规律。

学完这一章,你能够

  • 核对 Android Paint.setShader 的五大 Shader 子类(BitmapShader、ComposeShader、LinearGradient、RadialGradient、SweepGradient)与 TileMode(CLAMP、REPEAT、MIRROR)边界采样规律。

BitmapShader、TileMode 与 ComposeShader 构造解析

`Shader`(着色器/渲染器)用于为 `Paint` 提供超越单一纯色的纹理与渐变填充能力,其五大常用子类中,`BitmapShader(Bitmap bitmap, Shader.TileMode tileX, Shader.TileMode tileY)` 以位图作为填充纹理,`tileX` 与 `tileY` 控制绘制区域超出位图原始边界时的衔接模式:`CLAMP` 复制边缘像素颜色拉伸填充,`REPEAT` 按平铺方式周期重复,`MIRROR` 则在横向与纵向上做镜像翻转重复(本站实验已对越界坐标 `[-10, 0, 50, 100, 130, 210]` 逐点核验三种模式的采样索引)。

`ComposeShader(Shader shaderA, Shader shaderB, PorterDuff.Mode mode)` 借助 `PorterDuff.Mode` 混合模式把两种着色器(例如 `BitmapShader` 与 `LinearGradient`)叠加为复合纹理。需注意:在 Android 9(API 28)之前的硬件加速管线中,将两个同为 `BitmapShader` 的实例组合到 `ComposeShader` 曾存在限制,必要时需按需关闭单视图硬件加速或改用 `BlendMode`(API 29+)。

三大渐变 Shader:Linear、Radial 与 SweepGradient

`LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)` 沿起点 `(x0, y0)` 到终点 `(x1, y1)` 生成线性颜色渐变;`colors` 为颜色数组,`positions` 指定各颜色的归一化相对位置(范围 `0.0` 到 `1.0`,传入 `null` 时各色标均匀分布于 `i / (n - 1)`),`tile` 决定超出起止线段范围时的平铺模式。

`RadialGradient(float x, float y, float radius, int[] colors, float[] positions, Shader.TileMode tile)` 以 `(x, y)` 为圆心、`radius` 为半径向外做环形径向渐变;`SweepGradient(float cx, float cy, int[] colors, float[] positions)` 则以 `(cx, cy)` 为中心沿顺时针方向(0° 起对应正右方 `+X` 轴)扫描旋转一周形成雷达/色环式梯度渐变,由于单圈即覆盖 `360°`,因此构造时不需传入 `TileMode`。

BitmapShaderView 五区综合演示与工程要点

综合视图 `BitmapShaderView` 在 `init()` 中解码 `R.mipmap.img_cat` 并一次性初始化五个着色器,在 `onDraw()` 中依次演示:用 `ShapeDrawable(new OvalShape())` 配合 `BitmapShader(MIRROR, MIRROR)` 将图片裁为椭圆,随后分别用 `LinearGradient(REPEAT)`、`ComposeShader(..., DARKEN)`、`RadialGradient(REPEAT)` 与 `SweepGradient` 填充相邻矩形与圆形区域。需提示:`Shader` 默认基于 `Canvas` 原点坐标系采样,若目标绘制区域未与渐变坐标原点重合(如 `SweepGradient(30, 30)` 绘制在 `(bitW, bitH)` 处),应调用 `shader.setLocalMatrix(matrix)` 平移对齐,并避免在 `onDraw()` 中重复 `new ShapeDrawable`。来源页面附带的 `BitmapShaderDemo.zip` 因继承停采策略未联网下载,已单独登记留痕。

运行离线 Shader TileMode、Linear/Radial/SweepGradient 插值与 ComposeShader DARKEN 核验

含完整源码 · 172 行
展开查看收起
python
"""Offline Android graphics verifier for Ch 122: Paint Shader."""
import json
import math

VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"


def tile_coord(coord: float, size: float, mode: str) -> float:
    if mode == "CLAMP":
        return max(0.0, min(size - 1.0, coord))
    if mode == "REPEAT":
        return coord % size
    if mode == "MIRROR":
        period = 2.0 * size
        m = coord % period
        return m if m < size else (period - 1.0 - m)
    raise ValueError(mode)


def tile_t(t: float, mode: str) -> float:
    if mode == "CLAMP":
        return max(0.0, min(1.0, t))
    if mode == "REPEAT":
        return t % 1.0
    if mode == "MIRROR":
        m = t % 2.0
        return m if m <= 1.0 else 2.0 - m
    raise ValueError(mode)


def eval_gradient(t: float, colors: list[tuple[int, int, int]], positions: list[float] | None, mode: str) -> list[int]:
    if positions is None:
        n = len(colors)
        positions = [i / (n - 1) for i in range(n)]
    u = tile_t(t, mode)
    if u <= positions[0]:
        return list(colors[0])
    if u >= positions[-1]:
        return list(colors[-1])
    for i in range(len(positions) - 1):
        p0, p1 = positions[i], positions[i + 1]
        if p0 <= u <= p1:
            local = 0.0 if p1 == p0 else round((u - p0) / (p1 - p0), 12)
            c0, c1 = colors[i], colors[i + 1]
            return [int(round(c0[k] + local * (c1[k] - c0[k]))) for k in range(3)]
    return list(colors[-1])


def linear_t(x: float, y: float, x0: float, y0: float, x1: float, y1: float) -> float:
    dx, dy = x1 - x0, y1 - y0
    denom = dx * dx + dy * dy
    return ((x - x0) * dx + (y - y0) * dy) / denom


def radial_t(x: float, y: float, cx: float, cy: float, radius: float) -> float:
    return math.hypot(x - cx, y - cy) / radius


def sweep_t(x: float, y: float, cx: float, cy: float) -> float:
    ang = math.atan2(y - cy, x - cx)
    if ang < 0:
        ang += 2.0 * math.pi
    return ang / (2.0 * math.pi)


def porter_duff_darken_rgb(dst: tuple[int, int, int], src: tuple[int, int, int]) -> list[int]:
    # For opaque colors (alpha=1), PorterDuff.Mode.DARKEN computes min(dst, src) per channel
    return [min(dst[i], src[i]) for i in range(3)]


def main() -> None:
    # Case 1: BitmapShader TileMode CLAMP / REPEAT / MIRROR coordinate mapping on width=100
    probes = [-10, 0, 50, 100, 130, 210]
    c1_actual = {
        mode: [int(tile_coord(p, 100.0, mode)) for p in probes]
        for mode in ("CLAMP", "REPEAT", "MIRROR")
    }
    c1_expected = {
        "CLAMP": [0, 0, 50, 99, 99, 99],
        "REPEAT": [90, 0, 50, 0, 30, 10],
        "MIRROR": [9, 0, 50, 99, 69, 10],
    }

    # Case 2: LinearGradient(0,0,100,100, [RED, GREEN, BLUE, WHITE], null, REPEAT)
    colors_lin = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]
    lin_pts = [(0, 0), (50, 50), (100, 100), (150, 150)]
    c2_actual = {
        f"({x},{y})": eval_gradient(linear_t(x, y, 0, 0, 100, 100), colors_lin, None, "REPEAT")
        for x, y in lin_pts
    }
    # At (0,0): t=0 -> RED; at (50,50): t=0.5 (mid between GREEN@1/3 and BLUE@2/3) -> (0,128,128)
    # At (100,100): t=1.0 -> REPEAT 1.0%1.0 = 0.0 -> RED; at (150,150): t=1.5 -> 0.5 -> (0,128,128)
    c2_expected = {
        "(0,0)": [255, 0, 0],
        "(50,50)": [0, 128, 128],
        "(100,100)": [255, 0, 0],
        "(150,150)": [0, 128, 128],
    }

    # Case 3: RadialGradient(50,200,50) & SweepGradient(30,30) stop sampling
    colors_rg = [(0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 255, 255)]
    c3_actual = {
        "radial_center": eval_gradient(radial_t(50, 200, 50, 200, 50), colors_rg, None, "REPEAT"),
        "radial_half_r": eval_gradient(radial_t(75, 200, 50, 200, 50), colors_rg, None, "REPEAT"),
        "sweep_0deg": eval_gradient(sweep_t(60, 30, 30, 30), colors_rg, None, "CLAMP"),
        "sweep_90deg": eval_gradient(sweep_t(30, 60, 30, 30), colors_rg, None, "CLAMP"),
        "sweep_180deg": eval_gradient(sweep_t(0, 30, 30, 30), colors_rg, None, "CLAMP"),
    }
    c3_expected = {
        "radial_center": [0, 255, 0],
        "radial_half_r": [128, 0, 128],
        "sweep_0deg": [0, 255, 0],
        "sweep_90deg": [191, 64, 0],
        "sweep_180deg": [128, 0, 128],
    }

    # Case 4: ComposeShader(BitmapShader, LinearGradient, PorterDuff.Mode.DARKEN) + BitmapShaderView layout
    bit_w, bit_h = 200, 200
    darkened = porter_duff_darken_rgb((200, 180, 90), (120, 240, 150))
    c4_actual = {
        "compose_darken_rgb": darkened,
        "oval_bounds": [0, 0, bit_w, bit_h],
        "linear_rect": [bit_w, 0, bit_w * 2, bit_h],
        "compose_rect": [0, bit_h, bit_w, bit_h * 2],
        "radial_circle_center_r": [round(bit_w * 2.8, 1), bit_h / 2, bit_h / 2],
        "sweep_rect": [bit_w, bit_h, bit_w * 2, bit_h * 2],
    }
    c4_expected = {
        "compose_darken_rgb": [120, 180, 90],
        "oval_bounds": [0, 0, 200, 200],
        "linear_rect": [200, 0, 400, 200],
        "compose_rect": [0, 200, 200, 400],
        "radial_circle_center_r": [560.0, 100.0, 100.0],
        "sweep_rect": [200, 200, 400, 400],
    }

    cases = [
        {
            "name": "bitmap_shader_tilemode_mapping",
            "summary": "核验 BitmapShader 三种 TileMode(CLAMP/REPEAT/MIRROR)在越界坐标下的纹理采样映射",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "linear_gradient_stops_and_repeat",
            "summary": "核验 LinearGradient 四色均分(positions=null)与 REPEAT 平铺在斜向渐变上的 RGB 插值",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "radial_and_sweep_gradient_sampling",
            "summary": "核验 RadialGradient 径向归一化距离与 SweepGradient 360° 扫描角度的色标插值",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "compose_shader_darken_and_view_bounds",
            "summary": "核验 ComposeShader(PorterDuff.Mode.DARKEN) 通道叠加及 BitmapShaderView 五块区域绘制边界",
            "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()
验证 CLAMP/REPEAT/MIRROR 坐标映射、positions=null 四色均分线性/径向/扫描插值及 DARKEN 通道混合。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1943.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`positions` 为 `null` 时颜色数组按 `[0, 1/(n-1), ..., 1]` 均匀分布;若渐变坐标与目标图形不重合,应通过 `shader.setLocalMatrix(matrix)` 平移或缩放着色器局部矩阵,或在构造时直接使用目标图形坐标。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习