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

8.4.4 Android动画合集之属性动画-又见

核对 Android 属性动画高级特性:自定义 TypeEvaluator(PointEvaluator、ColorEvaluator)配合 ofObject、TimeInterpolator 内部数学公式(AccelerateDecelerate、Bounce 及自定义正弦插值器)与 ViewPropertyAnimator 链式用法。

学完这一章,你能够

  • 核对 Android 属性动画高级特性:自定义 TypeEvaluator(PointEvaluator、ColorEvaluator)配合 ofObject、TimeInterpolator 内部数学公式(AccelerateDecelerate、Bounce 及自定义正弦插值器)与 ViewPropertyAnimator 链式用法。

TypeEvaluator 原理与自定义 Point/Color 估值器

调用 `ValueAnimator.ofInt()` 与 `ofFloat()` 时,系统分别内置了 `IntEvaluator` 与 `FloatEvaluator`;若要通过 `ofObject()` 对自定义数据结构实现平滑过渡,则需实现 `TypeEvaluator<T>` 接口并重写 `evaluate(float fraction, T startValue, T endValue)`。其中 `fraction` 表示当前由插值器换算出的动画完成度,线性插值通式为 `startValue + fraction * (endValue - startValue)`。

基础示例定义仅含 `(x, y)` 坐标的 `Point` 类与 `PointEvaluator`,在自定义 `AnimView` 中通过 `ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint)` 驱动蓝色小球从左上角 `(RADIUS, RADIUS)` 移动到右下角 `(width - RADIUS, height - RADIUS)` 并不断 `invalidate()` 重绘。增强版 `AnimView2` 进一步编写 `ColorEvaluator`(按 ARGB 四通道独立线性插值,现代 API 21+ 也可直接使用系统内置的 `ArgbEvaluator`),在视图中提供 `getColor()`/`setColor(int)`,并用 `AnimatorSet` 将位置 `ValueAnimator` 与颜色 `ObjectAnimator` 以 `play(anim).with(objectAnimator)` 并行组合(配合 `setStartDelay(1000)` 与 `setDuration(3000)`),实现小球边位移边由蓝渐变至红(本站实验核验 `fraction=0.5` 时为 `#FF7F007F`)。

TimeInterpolator 内部数学模型与自定义插值器

属性动画新增了仅含单一方法 `getInterpolation(float input)` 的 `TimeInterpolator` 接口,原有补间动画的 `Interpolator` 均继承于此,因此可直接复用(如 `AccelerateInterpolator(2f)` 与 `BounceInterpolator`)。动画运行期间系统将随时间匀速递增的 `input ∈ [0, 1]` 传入 `getInterpolation(input)`,其返回值即为送入 `TypeEvaluator.evaluate()` 的 `fraction`:`LinearInterpolator` 原样返回 `input`;`BounceInterpolator` 按四段二次抛物线模拟自由落体弹跳;`AccelerateDecelerateInterpolator` 采用 `cos((input + 1) · π) / 2 + 0.5`,因余弦在 `[π, 2π]` 上两端斜率平缓、中段陡峭,自然形成先加速后减速曲线。自定义 `DecelerateAccelerateInterpolator` 则可分段采用 `sin(input · π) / 2`(`input < 0.5`)与 `1 - sin(input · π) / 2`(`input >= 0.5`),实现先减速后加速效果(本站实验已对四类插值器多采样点逐一核验)。

ViewPropertyAnimator 链式语法与绘图篇小结

Android 3.1(API 12)引入的 `ViewPropertyAnimator` 提供了面向 `View` 属性动画的极简声明式入口,例如 `textview.animate().x(500).y(500).setDuration(5000).setInterpolator(new BounceInterpolator())`。其核心特性有三点:① 一切调用均始于 `view.animate()` 返回的单一 `ViewPropertyAnimator` 实例;② 所有方法返回 `this`,支持任意深度的链式连缀;③ 配置完成后无需显式调用 `start()`,系统会在当前消息循环末尾自动启动(亦可手动调用 `start()` 提前触发),且底层会将多属性合并在单次 `invalidate` 中高效刷新。来源页面附带的 `AnimatorDemo3.zip` 因继承停采策略未联网下载,已单独登记留痕。

运行离线 PointEvaluator/ColorEvaluator 估值器、四类 TimeInterpolator 数学模型与 ViewPropertyAnimator 核验

含完整源码 · 186 行
展开查看收起
python
"""Offline Android animation verifier for Ch 131: TypeEvaluator, TimeInterpolator & ViewPropertyAnimator."""
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(frozen=True)
class Point:
    x: float
    y: float


def eval_point(fraction: float, start: Point, end: Point) -> list[float]:
    return [
        round(start.x + fraction * (end.x - start.x), 3),
        round(start.y + fraction * (end.y - start.y), 3),
    ]


def eval_color_argb(fraction: float, start_argb: int, end_argb: int) -> str:
    sa, sr, sg, sb = (start_argb >> 24) & 0xFF, (start_argb >> 16) & 0xFF, (start_argb >> 8) & 0xFF, start_argb & 0xFF
    ea, er, eg, eb = (end_argb >> 24) & 0xFF, (end_argb >> 16) & 0xFF, (end_argb >> 8) & 0xFF, end_argb & 0xFF
    a = int(sa + fraction * (ea - sa))
    r = int(sr + fraction * (er - sr))
    g = int(sg + fraction * (eg - sg))
    b = int(sb + fraction * (eb - sb))
    return f"#{a:02X}{r:02X}{g:02X}{b:02X}"


def bounce(t: float) -> float:
    return t * t * 8.0


def bounce_interpolator(t: float) -> float:
    # AOSP android.view.animation.BounceInterpolator
    t *= 1.1226
    if t < 0.3535:
        return bounce(t)
    if t < 0.7408:
        return bounce(t - 0.54719) + 0.7
    if t < 0.9644:
        return bounce(t - 0.8526) + 0.9
    return bounce(t - 1.0435) + 0.95


def accel_decel(t: float) -> float:
    return math.cos((t + 1.0) * math.pi) / 2.0 + 0.5


def decel_accel_custom(t: float) -> float:
    if t < 0.5:
        return math.sin(t * math.pi) / 2.0
    return 1.0 - math.sin(t * math.pi) / 2.0


class ViewPropertyAnimatorSim:
    def __init__(self) -> None:
        self.props: dict[str, float] = {}
        self.duration_ms: int = 300
        self.interpolator: str = "AccelerateDecelerateInterpolator"
        self.auto_start_scheduled: bool = False

    def alpha(self, val: float) -> "ViewPropertyAnimatorSim":
        self.props["alpha"] = val
        self.auto_start_scheduled = True
        return self

    def x(self, val: float) -> "ViewPropertyAnimatorSim":
        self.props["x"] = val
        self.auto_start_scheduled = True
        return self

    def y(self, val: float) -> "ViewPropertyAnimatorSim":
        self.props["y"] = val
        self.auto_start_scheduled = True
        return self

    def set_duration(self, ms: int) -> "ViewPropertyAnimatorSim":
        self.duration_ms = ms
        return self

    def set_interpolator(self, name: str) -> "ViewPropertyAnimatorSim":
        self.interpolator = name
        return self


def main() -> None:
    # Case 1: PointEvaluator on AnimView (RADIUS=80, 1080x1920 -> start(80,80), end(1000,1840))
    start_pt = Point(80.0, 80.0)
    end_pt = Point(1000.0, 1840.0)
    c1_actual = {
        "f_0_0": eval_point(0.0, start_pt, end_pt),
        "f_0_25": eval_point(0.25, start_pt, end_pt),
        "f_0_5": eval_point(0.5, start_pt, end_pt),
        "f_1_0": eval_point(1.0, start_pt, end_pt),
    }
    c1_expected = {
        "f_0_0": [80.0, 80.0],
        "f_0_25": [310.0, 520.0],
        "f_0_5": [540.0, 960.0],
        "f_1_0": [1000.0, 1840.0],
    }

    # Case 2: ColorEvaluator ARGB linear interpolation from Color.BLUE (#FF0000FF) to Color.RED (#FFFF0000)
    blue = 0xFF0000FF
    red = 0xFFFF0000
    c2_actual = {
        "f_0_0": eval_color_argb(0.0, blue, red),
        "f_0_5": eval_color_argb(0.5, blue, red),
        "f_1_0": eval_color_argb(1.0, blue, red),
    }
    c2_expected = {
        "f_0_0": "#FF0000FF",
        "f_0_5": "#FF7F007F",
        "f_1_0": "#FFFF0000",
    }

    # Case 3: TimeInterpolator formulas: Linear, Accelerate(2f), AccelerateDecelerate, Bounce, custom DecelerateAccelerate
    c3_actual = {
        "linear_0_5": 0.5,
        "accel_factor2_0_5": round(0.5 ** (2 * 2.0), 4),
        "accel_decel_samples": [round(accel_decel(t), 4) for t in (0.0, 0.25, 0.5, 0.75, 1.0)],
        "bounce_samples": [round(bounce_interpolator(t), 4) for t in (0.0, 0.3, 0.5, 0.8, 1.0)],
        "custom_decel_accel_samples": [round(decel_accel_custom(t), 4) for t in (0.0, 0.25, 0.5, 0.75, 1.0)],
    }
    c3_expected = {
        "linear_0_5": 0.5,
        "accel_factor2_0_5": 0.0625,
        "accel_decel_samples": [0.0, 0.1464, 0.5, 0.8536, 1.0],
        "bounce_samples": [0.0, 0.9074, 0.7016, 0.9165, 1.0001],
        "custom_decel_accel_samples": [0.0, 0.3536, 0.5, 0.6464, 1.0],
    }

    # Case 4: ViewPropertyAnimator fluent chaining & auto-start
    vpa = ViewPropertyAnimatorSim().x(500).y(500).set_duration(5000).set_interpolator("BounceInterpolator")
    c4_actual = {
        "props": vpa.props,
        "duration_ms": vpa.duration_ms,
        "interpolator": vpa.interpolator,
        "auto_start_scheduled": vpa.auto_start_scheduled,
    }
    c4_expected = {
        "props": {"x": 500, "y": 500},
        "duration_ms": 5000,
        "interpolator": "BounceInterpolator",
        "auto_start_scheduled": True,
    }

    cases = [
        {
            "name": "point_type_evaluator_interpolation",
            "summary": "核验自定义 PointEvaluator 在 RADIUS=80 起点 (80,80) 到终点 (1000,1840) 的线性坐标插值",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "color_type_evaluator_argb_blend",
            "summary": "核验 ColorEvaluator 按 ARGB 四通道从 Color.BLUE 到 Color.RED 的整型截断插值",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "time_interpolator_math_models",
            "summary": "核验 Accelerate(2f)、AccelerateDecelerate、Bounce 及自定义 DecelerateAccelerate 插值曲线",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "view_property_animator_fluent_chain",
            "summary": "核验 ViewPropertyAnimator 连缀调用 x(500).y(500).setDuration(5000) 及自动启动标记",
            "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()
验证 Point 线性插值、ARGB 通道混合 #FF7F007F、Bounce/AccelerateDecelerate/自定义插值采样及连缀自动启动。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

系统按经过时长与总时长之比算出线性时间进度 `input ∈ [0, 1]` 交给 `TimeInterpolator.getInterpolation(input)`,该函数计算出的非线性结果直接作为 `fraction` 传入 `TypeEvaluator.evaluate(fraction, startValue, endValue)` 来决定最终属性值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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