惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
罗磊的独立博客
Martin Fowler
Martin Fowler
博客园_首页
Stack Overflow Blog
Stack Overflow Blog
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
B
Blog
C
Check Point Blog
WordPress大学
WordPress大学
G
Google Developers Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
量子位
月光博客
月光博客
U
Unit 42
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Jina AI
Jina AI
S
Secure Thoughts
aimingoo的专栏
aimingoo的专栏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
Latest news
Latest news
V
Vulnerabilities – Threatpost
D
Docker
Attack and Defense Labs
Attack and Defense Labs
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Forbes - Security
Forbes - Security
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
Cloudbric
Cloudbric
Spread Privacy
Spread Privacy

博客园_首页

Plist 二进制格式 Milvus 和 PGVector,哪个更好? OpenClaw 已过时?在 VS Code 中运行 Hermes Agent! 第30篇文章:一个大三计科生的自白 Manim如何在数学公式中完美显示中文? Docker 部署 RocketMQ 5 并发编程核心概念辨析 C#事务处理最佳实践:别再让“主表存了、明细丢了”的破事发生 CLI 是什么?为什么大厂突然集体卷命令行? 【从0到1构建一个ClaudeAgent】协作-自主Agent UIImageView 设置图片不生效的原因排查 最小二乘问题详解20:无先验约束下的增量式SFM自由网平差 痞子衡嵌入式:大话双核i.MXRT1180之XIP应用里借助MU实现可靠Flash IAP的方法 AI Chat 封装, SemanticKerne.AiProvider.Unified 已发布 Windows下右键编辑js文件无法打开记事本——在注册表中使用环境变量 在后台服务中使用 Scoped 服务,为什么总是报错? H200 安装驱动并使用sglang启动模型 wireshark 抓包Trap上报告警内容 我用 AI 辅助开发了一系列小工具(2):图片压缩工具 [A Primer On MC and CC] 2.1 Memory Consistency 1 - 指令重排序和 SC 模型 Oracle数据库SCN推进技术详解与实践指南 玩转控件:封装个带图片的Label控件 Claude Code 4.7 真正该升级的不是模型,而是你的工作流 前端小白一句话,AI 帮我做了个颜值拉满的桌面媒体播放器。当代码不再是门槛,一句话编程就是现实。 5. WorkBuddy: 小龙虾的灵魂三件套,让你的小龙虾不只是工具 SQLite 分片方案实战:三种分片策略的深度对比 告别简陋 UI!一款基于 Fluent Design 和基于 WinUI 的开源免费、现代化的 Avalonia UI 控件库 关于二进制排列组合枚举的总结 AI开发-python-LangGraph框架(3-27-LangGraph从零实现大模型智能决策工作流) ElasticSearch主分片和副本分片概念详解 【002】HTTPS 粗解:证书、TLS 握手与对后端配置的影响 Hermes Agent 一周暴涨五万 Star,但我劝你别急着追 明明连接的是Redis的DB0,为什么能查到DB3的数据? 【从0到1构建一个ClaudeAgent】协作-Agent团队 熟悉电子元器件之后,电子小白下一步该怎么走? MAF快速入门(23)通过C#类定义Skills .NET 高级开发 | 手写一个对象映射框架 FastAPI数据库ORM怎么选?我肝了三个Demo后,终于不再纠结了 mysqldump 参数拾遗:在遗忘与铭记之间 C# .NET 周刊|2026年3月5期 Claude code入门 - 陈彦斌 一文学习入门 ThingsBoard 开源物联网平台 GitHub 热门项目 | 2026年04月16日 如何为GIT设置全局勾子,为每次提交追加信息 Number.isFinite和isFinite与isNaN()和Number.isNaN的区别 PortSwigger SQL注入LAB2 推荐一个测试人必备的Skills,从功能到性能全搞定(附详细实操和安装下载方式) 筑基期:掌握Odoo基础核心知识点02(Odoo XML 开发方式详解) GLM模型这么火,咱们用vllm也咧一个呗! 深入理解 AbortController:从底层原理到跨语言设计哲学 字符串学习笔记 多租户系统框架的基础模块设计和分析设计 Apache SeaTunnel Zeta 为什么能做到“又快又稳”? AI开发-python-LangGraph框架(3-26-LangGraph基本概念及第一个简单样例) Vue 3 组件通信,别只会用 Props 和 Emits 了,这几个狠活儿你得看看 ElasticSearch7.X版本配置密码 用Manim实现动态交点计算--从一个动点问题说起 团结引擎+Addressable+Instant Game打包抖音小游戏 function call 实战:让 LLM 自动判断 pod 异常、调用日志工具并完成故障分析 bubseek —— 让 Agent 的足迹,变成团队的洞察 通过 C# 读取并导出 PDF 书签 如何用 GitHub Actions 实现 Steam 自动化发布 【从0到1构建一个ClaudeAgent】并发-后台任务 .NET 高级开发 | 定制 ASP.NET Core 框架 电子小白:什么是运算放大器(运放) zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线 堆上的ORW HC32F460 USB CDC通信异常:非对齐访问异常排查 20260413-Hyperbridge 攻击事件:发生在默克尔山上的验证绕过 那些喊着AI 要淘汰你的人,正在靠你的焦虑赚大钱! 深度学习进阶(八)Swin Transformer 最小二乘问题详解19:带先验约束的增量式SFM优化与实现 SnapTranslate 3.0 正式发布:全局划词翻译 + 完整英语学习闭环,一站式搞定查词、记词、复习 工作的意义、工作的困难认知再思考 .NET + AI 进阶实战:基于类的技能开发 - 打造可治理的 Agent 能力模块 【从0到1构建一个ClaudeAgent】规划与协调-技能 上周热点回顾(4.6-4.12) 电子小白的工具三件套:面包板、杜邦线、万能板 单表五亿数据的查询优化 | Mysql、StarRocks 2. WorkBuddy:从“我是谁”到“帮我干活” C# 如何减少代码运行时间:7 个实战技巧 基于HelixToolkit.SharpDX 渲染3D模型 - 笺上知微 从零开始的双臂具身VLA起源及现阶段发展综述 - SkyXZ 记对 xonsh shell 的使用, 脚本编写, 迁移及调优 - pluvium27 受够了Vibe Coding的失控?换个起点,让AI事半功倍 从开始配置漏洞环境到漏洞复现流程 - 難しい 关于10年工作经验的程序员对OpenClaw的实战经验分享以及看法 - 虚无境 Any metadata 的内存布局 C# .NET 周刊|2026年3月2期 - InCerry 我帮你测过了,测试圈排名第二的 Skill 依然很牛逼 Skill Discovery | 无监督技能发现的经典工作总结 - MoonOut 上下文工程是什么?过时了么?一文讲明白! - 一枫说码 开了 TUN 模式还是直连?90% 的人都踩过这个坑 AScript扩展多种脚本语言 - rockey627 AI 学习笔记:Agent 的记忆机制 你能被装进一个文件里吗?——7 万人把同事"蒸馏"成了 AI - 我没有三颗心脏 Claude Code 通关手册(七):给 AI 装上技能包——Skills 完全指南 - 暮色之狐 在浏览器中快速编辑代码:VSCode Web 集成实践 - Newbe36524 蒸馏自己 skill?基于 Deepseek 的蒸馏器,丐版蒸馏方式,简单便捷 - To_Carpe_Diem Spring AI Aliababa和AgentScope,哪个更好? - 苏三说技术
Avalonia中的动画
Wuya · 2026-05-22 · via 博客园_首页

作者:王先荣
内置动画 在Avalonia中,常用的动画有以下几种:关键帧动画(KeyFrame Animation)、过渡动画(Transition Animation)和合成动画(Composition Animations)。它们在使用方式和适用场景有所不同,官方文档的总结如下表所示(https://docs.avaloniaui.net/docs/graphics-animation/animations)。

Type
Description
Use case
Keyframe Animations
 
Change one or more properties over a timeline with multiple keyframes.
 
Complex, multi-step animations triggered by style selectors.
 
Control Transitions
 
Animate a single property when its value changes.
 
Smooth visual feedback for property changes (opacity, color, size).
 
Composition Animations
 
Code-driven animations that run on the render thread.
 
Performance-sensitive or programmatic animations controlled from C#.

严格来说,它们都是插值动画(Interpolated Animations)。那么怎样才能实现离散动画呢?例如打字机效果的动画,游戏中的精灵动画。 Avalonia官方的自定义动画示例 Avalonia的官方示例项目(RenderDemo https://github.com/AvaloniaUI/Avalonia/tree/master/samples/RenderDemo)中,实现了一个名为CustomStringAnimator(https://github.com/AvaloniaUI/Avalonia/blob/master/samples/RenderDemo/Pages/CustomStringAnimator.cs)的动画类,它继承自InterpolatingAnimator<string>,并重写了Interpolate方法来实现打字机效果的动画。以下是该动画类的代码:

public class CustomStringAnimator : InterpolatingAnimator<string>
{
    public override string Interpolate(double progress, string oldValue, string newValue)
    {
        if (newValue.Length == 0) return "";
        var step = 1.0 / newValue.Length;
        var length = (int)(progress / step);
        var result = newValue.Substring(0, length + 1);
        return result;
    }
}

自定义动画

使用起来跟普通的动画几乎一样,需要指定Animator,代码如下(https://github.com/AvaloniaUI/Avalonia/blob/master/samples/RenderDemo/Pages/CustomAnimatorPage.xaml):

<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
  <TextBlock.Styles>
    <Style Selector="TextBlock">
      <Style.Animations>
        <Animation Duration="0:0:1" IterationCount="Infinite">
          <KeyFrame Cue="0%">
            <Setter Property="Text" Value="">
              <Animation.Animator>
                <pages:CustomStringAnimator/>
              </Animation.Animator>
            </Setter>
          </KeyFrame>
          <KeyFrame Cue="100%">
            <Setter Property="Text" Value="0123456789" >
              <Animation.Animator>
                <pages:CustomStringAnimator/>
              </Animation.Animator>
            </Setter>
          </KeyFrame>
        </Animation>
      </Style.Animations>
    </Style>
  </TextBlock.Styles>
</TextBlock>

View Code

值得注意的是在axaml中使用自定义动画器时,需要指定动画器的类型(<Animation.Animator><pages:CustomStringAnimator/></Animation.Animator>),否则会报错。 改进的字符串动画 在官方示例的基础上,我们可以略微做一些改进:支持在字符串之间进行插值动画。动画过程中会根据进度逐渐显示新字符串的内容,同时保留旧字符串的公共前缀部分。

public class StringAnimator : InterpolatingAnimator<string>
{
    /// <summary>
    /// 计算插值结果。
    /// </summary>
    /// <param name="progress">进度:0到1之间的值,指在两个关键帧之间过渡的时间位置。</param>
    /// <param name="oldValue">旧值:动画开始时,第一个关键帧的值。</param>
    /// <param name="newValue">新值:动画结束时,最后一个关键帧的值。</param>
    /// <returns>返回插值结果。</returns>
    public override string Interpolate(double progress, string oldValue, string newValue)
    {
        if (progress <= 0)
            return oldValue;
        if (progress >= 1)
            return newValue;
        int oldLength = string.IsNullOrEmpty(oldValue) ? 0 : oldValue.Length;
        int newLength = string.IsNullOrEmpty(newValue) ? 0 : newValue.Length;
        if (oldLength == 0 && newLength == 0)
            return string.Empty;
        if (oldLength == newLength && oldValue == newValue)
            return newValue;
        if (oldLength == 0 || newValue.StartsWith(oldValue))
        {
            // 如果旧值为空或新值以旧值开头,则从旧值开始插入新值的剩余部分
            return newValue.Substring(0, (int)(oldLength + (newLength - oldLength) * progress));
        }
        else if (newLength == 0 || oldValue.StartsWith(newValue))
        {
            // 如果新值为空或旧值以新值开头,则从新值开始删除旧值的剩余部分
            return oldValue.Substring(0, (int)(newLength + (oldLength - newLength) * (1 - progress)));
        }
        else
        {
            //如果没有包含关系,忽略旧值,直接从新值开始插入
            oldLength = 0;
            return newValue.Substring(0, (int)(oldLength + (newLength - oldLength) * progress));
        }
    }

    static StringAnimator()
    {
        // 注册动画器
        Animation.RegisterCustomAnimator<string, StringAnimator>();
    }
}

使用方法跟官方示例一样。 自定义离散动画 如果要实现通用的离散动画,该怎么实现呢?跟上面类似,我们可以从InterpolatingAnimator<T>继承一个DiscreteAnimator<T>类,代码很简单,放弃中间的过渡部分,直接在进度达到100%时切换到新值,代码如下:

public class DiscreteAnimator<T> : InterpolatingAnimator<T>
{
    public override T Interpolate(double progress, T oldValue, T newValue)
    {
        return progress < 1 ? oldValue : newValue;
    }

    static DiscreteAnimator()
    {
        // 注册动画器
        Animation.RegisterCustomAnimator<T, DiscreteAnimator<T>>();
    }
}

使用方法跟上面一样:

<TextBlock Text="离散动画器文本,切换几种不同的样式。">
    <TextBlock.Styles>
        <Style Selector="TextBlock">
          <Style.Animations>
            <Animation Duration="0:0:3" IterationCount="Infinite" PlaybackDirection="Alternate">
              <KeyFrame Cue="0%">
                <Setter Property="FontStyle" Value="Normal">
                    <Animation.Animator>
                        <app:DiscreteAnimator x:TypeArguments="FontStyle" />
                    </Animation.Animator>
                </Setter>
              </KeyFrame>
              <KeyFrame Cue="30%">
                <Setter Property="FontStyle" Value="Italic">
                    <Animation.Animator>
                        <app:DiscreteAnimator x:TypeArguments="FontStyle" />
                    </Animation.Animator>
                </Setter>
              </KeyFrame>
              <KeyFrame Cue="60%">
                <Setter Property="FontStyle" Value="Oblique">
                    <Animation.Animator>
                        <app:DiscreteAnimator x:TypeArguments="FontStyle" />
                    </Animation.Animator>
                </Setter>
              </KeyFrame>
            </Animation>
          </Style.Animations>
        </Style>
      </TextBlock.Styles>
</TextBlock>

因为我们使用了泛型,在指定动画器时需要使用x:TypeArguments来指定类型参数(<app:DiscreteAnimator x:TypeArguments="FontStyle" />),否则会报错。 另一种实现自定义动画的变通方法 如果不想实现通用的动画器,我们可以注册AvaloniaProperty,并在属性的PropertyChanged回调中直接修改属性值来实现动画效果。以下是一个简单的示例,演示如何通过注册一个名为DiscreteValue的AvaloniaProperty来实现几何路径变换的动画:

//注册一个AvaloniaProperty,类型为int,默认值为0
public const string DISCRETE_VALUE = "DiscreteValue";
public static readonly StyledProperty<int> DiscreteValueProperty =
    AvaloniaProperty.Register<Path, int>(DISCRETE_VALUE, 0);
//定义一个数组,存储不同的几何路径,在动画过程中根据DiscreteValue的值来切换不同的路径
private PathGeometry[] bells = [];      //这里省略了路径的定义
//创建一个动画并运行它
private void PlayAnimation_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
    var animation = new Animation()
    {
        Duration = TimeSpan.FromSeconds(8),
        IterationCount = new IterationCount(2),
        PlaybackDirection = PlaybackDirection.Alternate,
        Children =
        {
            new KeyFrame()
            {
                Setters = { new Setter(DiscreteValueProperty, 0), },
                KeyTime = TimeSpan.FromSeconds(0)
            },
            new KeyFrame()
            {
                Setters = { new Setter(DiscreteValueProperty, 1), },
                KeyTime = TimeSpan.FromSeconds(2)
            },
            new KeyFrame()
            {
                Setters = { new Setter(DiscreteValueProperty, 2), },
                KeyTime = TimeSpan.FromSeconds(4)
            },
            new KeyFrame()
            {
                Setters = { new Setter(DiscreteValueProperty, 3), },
                KeyTime = TimeSpan.FromSeconds(6)
            },
            new KeyFrame()
            {
                Setters = { new Setter(DiscreteValueProperty, 3), },
                KeyTime = TimeSpan.FromSeconds(8)
            }
        }
    };
    _ = animation.RunAsync(Path1);
}
//在属性的PropertyChanged事件中,根据DiscreteValue的值来切换不同的路径
private void Path1_PropertyChanged(object? sender, Avalonia.AvaloniaPropertyChangedEventArgs e)
{
    if (e.Property.Name == DiscreteValueProperty.Name)
    {
        Debug.WriteLine($"time: {DateTime.Now}, Path1 property changed: {e.Property.Name}, old value: {e.OldValue}, new value: {e.NewValue}");
        int value = (int)e.NewValue;
        Path1.Data = bells[value % bells.Length];
    }
}

这种方法只能在代码中调用,无法在axaml中使用,但它不需要实现通用的动画器,适合一些特定的动画效果。 本文相关代码可以在我的Gitee仓库中找到: https://gitee.com/xrwang2/avalonia-test/tree/master/AvaloniaMvvpDesktopApp