HarmonyOS鸿蒙Next如何通过属性动画实现网络连接加载动效示例demo?
HarmonyOS鸿蒙Next如何通过属性动画实现网络连接加载动效示例demo? 应用与其他特定服务器网络连接时,在等待和连接成功时需要展示动画,实现更好的人机交互
3 回复
参考文档:通过属性动画实现网络连接的动效
更多关于HarmonyOS鸿蒙Next如何通过属性动画实现网络连接加载动效示例demo?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
鸿蒙Next中可通过属性动画实现网络加载动效。使用AnimatorProperty设置目标组件属性变化,如旋转角度、透明度等。示例代码片段:
// 创建动画对象
const animator = this.animator.createAnimator({
duration: 1000,
iterations: -1 // 无限循环
});
// 设置旋转动画
animator.onFrame((fraction: number) => {
this.rotateAngle = fraction * 360;
});
// 启动动画
animator.play();
通过修改rotateAngle绑定到组件的rotate属性实现旋转效果。
在HarmonyOS Next中,可以通过属性动画(Property Animation)结合Canvas绘制或组件属性变化来实现网络连接加载动效。以下是一个简洁的实现示例:
核心思路
- 使用
AnimatorProperty或animateTo方法驱动动画。 - 通过插值计算(如线性插值)动态更新动画属性(如旋转角度、透明度、路径进度)。
- 结合Canvas绘制自定义动效,或使用系统组件(如
LoadingProgress)扩展。
示例代码(基于Canvas绘制旋转加载动效)
import { animator, Curve, curves } from '@kit.ArkUI';
@Entry
@Component
struct NetworkLoadingDemo {
private angle: number = 0; // 旋转角度
private animator: animator.AnimatorResult | null = null;
// 绘制Canvas动效
private drawLoading(context: CanvasRenderingContext2D, size: Size) {
context.clearRect(0, 0, size.width, size.height);
const centerX = size.width / 2;
const centerY = size.height / 2;
const radius = Math.min(size.width, size.height) * 0.3;
// 绘制背景圆环
context.beginPath();
context.arc(centerX, centerY, radius, 0, Math.PI * 2);
context.strokeStyle = '#E5E5E5';
context.lineWidth = 8;
context.stroke();
// 绘制动态进度圆环
context.beginPath();
context.arc(centerX, centerY, radius, 0, this.angle * Math.PI / 180);
context.strokeStyle = '#007DFF';
context.lineWidth = 8;
context.lineCap = 'round';
context.stroke();
}
// 启动动画
startAnimation() {
this.animator = animator.create({
duration: 1000, // 动画时长
iterations: -1, // 无限循环
curve: Curve.Linear, // 线性曲线
onUpdate: (value: number) => {
this.angle = value * 360; // 角度从0°到360°
this.canvasContext?.requestAnimationFrame(); // 触发Canvas重绘
}
});
this.animator.play();
}
// 停止动画(连接成功时调用)
stopAnimation() {
this.animator?.pause();
// 可添加连接成功后的过渡动画,如缩放消失
animateTo({
duration: 300,
curve: curves.springMotion(),
}, () => {
this.angle = 0; // 重置角度
});
}
build() {
Column() {
// Canvas绘制动效
Canvas(this.drawLoading)
.width(100)
.height(100)
.onReady(() => this.startAnimation()) // 组件就绪后启动动画
// 模拟网络连接控制按钮
Button('模拟连接成功')
.onClick(() => this.stopAnimation())
.margin(20)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
关键点说明
- 动画驱动:使用
animator.create创建属性动画,通过onUpdate回调更新旋转角度。 - Canvas绘制:动态角度值传递给Canvas的
drawLoading方法,实现圆环进度动画。 - 交互控制:通过
startAnimation和stopAnimation控制动画启停,连接成功后可切换为成功状态动画。 - 扩展建议:可结合
LoadingProgress组件或Lottie动画实现更复杂效果,通过animateTo调整组件透明度、缩放等属性增强交互反馈。
此示例展示了基础实现,实际可根据需求调整动画曲线、时长及绘制样式。

