蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 ValueAnimator 轨迹方程、ObjectAnimator setter 映射及 AnimatorSet/XML 时序核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-valueanimator.py
explore-tutorial-valueanimator.py164 行
"""Offline Android animation verifier for Ch 130: ValueAnimator, ObjectAnimator & AnimatorSet."""
import json
import math
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

ANIMATOR_SET_XML = """<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:ordering="sequentially">
    <set>
        <objectAnimator android:duration="500" android:propertyName="x" android:valueTo="400" android:valueType="intType" />
        <objectAnimator android:duration="500" android:propertyName="y" android:valueTo="300" android:valueType="intType" />
    </set>
    <objectAnimator android:duration="500" android:propertyName="alpha" android:valueTo="1f" />
</set>
"""


def eval_keyframes(values: list[float], fraction: float) -> float:
    n = len(values) - 1
    scaled = fraction * n
    idx = min(n - 1, int(math.floor(scaled)))
    local = scaled - idx
    return values[idx] + local * (values[idx + 1] - values[idx])


def schedule_animator_set(root: ET.Element, start_ms: int = 0) -> tuple[list[dict], int]:
    ordering = root.attrib.get(f"{ANDROID_NS}ordering", "together")
    cursor = start_ms
    max_end = start_ms
    events: list[dict] = []
    for child in root:
        if child.tag == "set":
            sub_ev, sub_end = schedule_animator_set(child, cursor)
            events.extend(sub_ev)
            if ordering == "sequentially":
                cursor = sub_end
            max_end = max(max_end, sub_end)
        else:
            dur = int(child.attrib[f"{ANDROID_NS}duration"])
            prop = child.attrib[f"{ANDROID_NS}propertyName"]
            ev = {"property": prop, "start_ms": cursor, "end_ms": cursor + dur}
            events.append(ev)
            if ordering == "sequentially":
                cursor += dur
            max_end = max(max_end, ev["end_ms"])
    return events, max_end


def main() -> None:
    # Case 1: ValueAnimator multi-keyframe lineAnimator & circleAnimator parametric orbit
    w, h = 800, 1000
    line_vals = [h, 0, h / 4, h / 2, h / 4 * 3, h]
    # 5 segments: f=0.0->1000, f=0.2->0, f=0.6->500, f=1.0->1000
    sampled_line = [int(round(eval_keyframes(line_vals, f))) for f in (0.0, 0.2, 0.6, 1.0)]
    radius = w // 4  # 200
    orbit_pts = []
    for f in (0.0, 0.25, 0.5, 0.75):
        t = f * 2.0 * math.pi
        orbit_pts.append([int(round(radius * math.sin(t) + w / 2)), int(round(radius * math.cos(t) + h / 2))])
    c1_actual = {
        "line_animator_y_samples": sampled_line,
        "circle_orbit_xy_samples": orbit_pts,
    }
    c1_expected = {
        "line_animator_y_samples": [1000, 0, 500, 1000],
        "circle_orbit_xy_samples": [[400, 700], [600, 500], [400, 300], [200, 500]],
    }

    # Case 2: ObjectAnimator getter/setter naming & multi-keyframe alpha/rotation/scaleX
    def setter_name(prop: str) -> str:
        return "set" + prop[0].upper() + prop[1:]

    alpha_kf = [1.0, 0.0, 1.0, 0.0, 1.0]
    scale_kf = [2.0, 4.0, 1.0, 0.5, 1.0]
    c2_actual = {
        "setters": [setter_name(p) for p in ("alpha", "rotation", "scaleX", "translationY")],
        "alpha_at_0_25_and_0_5": [eval_keyframes(alpha_kf, 0.25), eval_keyframes(alpha_kf, 0.5)],
        "scaleX_at_0_25_and_0_75": [eval_keyframes(scale_kf, 0.25), eval_keyframes(scale_kf, 0.75)],
    }
    c2_expected = {
        "setters": ["setAlpha", "setRotation", "setScaleX", "setTranslationY"],
        "alpha_at_0_25_and_0_5": [0.0, 1.0],
        "scaleX_at_0_25_and_0_75": [4.0, 0.5],
    }

    # Case 3: AnimatorSet Builder: play(anim4).with(anim3).with(anim2).after(anim1)
    # anim1 runs [0, 5000], then anim2/anim3/anim4 run concurrently [5000, 10000]
    dur = 5000
    timeline = {
        "animator1": [0, dur],
        "animator2": [dur, dur * 2],
        "animator3": [dur, dur * 2],
        "animator4": [dur, dur * 2],
    }
    c3_actual = {
        "builder_timeline_ms": timeline,
        "total_duration_ms": dur * 2,
        "listener_callbacks": ["onAnimationStart", "onAnimationRepeat", "onAnimationEnd", "onAnimationCancel"],
    }
    c3_expected = {
        "builder_timeline_ms": {
            "animator1": [0, 5000],
            "animator2": [5000, 10000],
            "animator3": [5000, 10000],
            "animator4": [5000, 10000],
        },
        "total_duration_ms": 10000,
        "listener_callbacks": ["onAnimationStart", "onAnimationRepeat", "onAnimationEnd", "onAnimationCancel"],
    }

    # Case 4: XML <set ordering="sequentially"> nested <set> (default together) timing
    root = ET.fromstring(ANIMATOR_SET_XML)
    events, total_ms = schedule_animator_set(root)
    c4_actual = {
        "events": events,
        "total_ms": total_ms,
    }
    c4_expected = {
        "events": [
            {"property": "x", "start_ms": 0, "end_ms": 500},
            {"property": "y", "start_ms": 0, "end_ms": 500},
            {"property": "alpha", "start_ms": 500, "end_ms": 1000},
        ],
        "total_ms": 1000,
    }

    cases = [
        {
            "name": "value_animator_keyframes_and_circle_orbit",
            "summary": "核验 ValueAnimator 多关键帧折线采样及圆参数方程 x=R*sin(t)+w/2, y=R*cos(t)+h/2 轨迹",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "object_animator_property_setters_and_values",
            "summary": "核验 ObjectAnimator 属性名到 setter 方法映射及多段 alpha/scaleX 关键帧插值",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "animator_set_builder_and_listener_contract",
            "summary": "核验 AnimatorSet play/with/after 编排时序及 AnimatorListener 四项回调契约",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "animator_xml_nested_set_scheduling",
            "summary": "核验 res/animator XML 中外层 sequentially 与内层默认 together 组合动画时间轴",
            "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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-valueanimator-lab/explore-tutorial-valueanimator.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-valueanimator.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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