HarmonyOS鸿蒙Next中video组件src更新时如何添加scaleIn和scaleOut动画

HarmonyOS鸿蒙Next中video组件src更新时如何添加scaleIn和scaleOut动画

video 组件 他的 src 会在某种场景下会更新视频,我想在更新视频的时候加一个 scaleIn 和 scaleOut 的动画,该怎么实现

4 回复

@Component struct AnimatedVideoPlayer { @State currentSrc: Resource = $rawfile(‘video1.mp4’) private animator: Animator = new Animator() private scale: number = 1 aboutToAppear() { this.animator = new Animator({ duration: 300, curve: Curve.EaseInOut }); } } build() { Stack({ alignContent: Alignment.Center }) { Video({ src: this.currentSrc, controller: new VideoController() }) .scale({ x: this.scale, y: this.scale }) .width(‘100%’) .height(‘100%’) } .width(‘100%’) .height(‘100%’) } // 切换视频方法 async changeVideo(newSrc: Resource) { // 缩小动画 await this.animateScale(1, 0);

// 更新视频源 this.currentSrc = newSrc;

// 等待一帧确保视频组件更新 await new Promise(resolve => setTimeout(resolve, 50));

// 放大动画 await this.animateScale(0, 1); } // 执行缩放动画 private animateScale(from: number, to: number): Promise<void> { return new Promise(resolve => { this.animator.onframe = (value: number) => { this.scale = from + (to - from) * value; }; this.animator.onfinish = () => { resolve(); }; this.animator.play(); }); }

更多关于HarmonyOS鸿蒙Next中video组件src更新时如何添加scaleIn和scaleOut动画的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


标题

文本内容。

子标题

更多文本内容。

在HarmonyOS鸿蒙Next中,为video组件src更新添加scaleIn和scaleOut动画,可使用ArkUI的animation属性配合属性动画。具体实现:在video组件外层包裹stack或column容器,通过设置transition和animateTo方法控制缩放效果。scaleIn动画可用transformScale从0到1,scaleOut从1到0,持续时长通过animationDuration调节。动画触发时机应在src属性变更前/后的状态回调中处理。示例代码框架:

@State scaleValue: number = 1;
// 切换src时
animateTo({ duration: 500 }, () => {
  this.scaleValue = 0; // scaleOut
  this.src = newSrc;
  this.scaleValue = 1; // scaleIn
})

在HarmonyOS Next中,可以通过ArkUI的动画能力为video组件实现src更新时的scaleIn/scaleOut效果。以下是实现方案:

  1. 使用显式动画配合状态变量:
@State scale: number = 1
@State opacity: number = 1

Video({
  src: this.videoSrc
})
.scale({ x: this.scale, y: this.scale })
.opacity(this.opacity)
.onClick(() => {
  // 先执行scaleOut
  animateTo({
    duration: 300,
    curve: Curve.EaseOut
  }, () => {
    this.scale = 0.8
    this.opacity = 0
  })

  // 更新视频源
  this.videoSrc = 'new_video.mp4'

  // 再执行scaleIn
  animateTo({
    duration: 300,
    curve: Curve.EaseIn
  }, () => {
    this.scale = 1
    this.opacity = 1
  })
})
  1. 使用转场动画(transition):
@State isChanged: boolean = false

Video({
  src: this.videoSrc
})
.scale(this.isChanged ? 0.8 : 1)
.opacity(this.isChanged ? 0 : 1)
.transition(TransitionEffect.OPACITY
  .combine(TransitionEffect.scale({ x: 0.8, y: 0.8 }))
  .animation({ duration: 300, curve: Curve.EaseInOut })
)
.onClick(() => {
  this.isChanged = true
  this.videoSrc = 'new_video.mp4'
  this.isChanged = false
})

注意事项:

  1. 确保在动画完成后才更新视频源
  2. 调整duration参数控制动画速度
  3. 可根据需要组合其他动画效果

这两种方案都能实现平滑的缩放过渡效果,第一种方案控制更精细,第二种方案代码更简洁。

回到顶部