harmony 鸿蒙Frame Animation (ohos.animator)

  • 2025-06-12
  • 浏览 (3)

Frame Animation (ohos.animator)

The frame animation allows you to adjust your animation properties on each frame, thanks to its per-frame callback. By leveraging the onFrame callback, you can dynamically set property values on each frame, creating smooth and natural animations. For details about the frame animation APIs, see @ohos.animator (Animator).

Compared with the property animation, the frame animation offers the benefits of real-time visibility into the animation process and allows you to modify UI values on the fly. In addition, it provides high responsiveness to events and can be paused as needed. However, it is worth noting that the frame animation may not be as performant as the property animation. Therefore, where the property animation meets the requirements, you are advised to use the property animation APIs. For details, see Implementing Property Animation. The table below provides a comparison between the property animation and frame animation.

Name Implementation Event Response Pausable Performance
Frame animation (ohos.animator) Allows real-time modification and updating of UI properties on each frame. Responds in real time Yes Relatively lower
Property animation Calculates the final state of the animation, with the UI reflecting only the end state, not the intermediate rendering values. Responds to the end state No Generally higher

The following figures illustrate the difference: The frame animation offers real-time responsiveness, whereas the property animation reacts to the final state of the animation.

Alt text

Alt text

Using Frame Animation to Implement Animation Effects

To create a simple animator and print the current interpolation value in each frame callback:

  1. Import dependencies.
   import { AnimatorOptions, AnimatorResult } from '@kit.ArkUI';
  1. Create an animator object.
   // Initial options for creating an animator object
   let options: AnimatorOptions = {                        
      duration: 1500,                               
      easing: "friction",                        
      delay: 0,                           
      fill: "forwards",                                  
      direction: "normal",                                  
      iterations: 2,                                        
      // Initial frame value used for interpolation in the onFrame callback                             
      begin: 200.0,                                         
      // End frame value used for interpolation in the onFrame callback                                
      end: 400.0                                            
   }; 
   let result: AnimatorResult = this.getUIContext().createAnimator(options);
   // Set up a callback for when a frame is received, so that the onFrame callback is called for every frame throughout the animation playback process.
       result.onFrame = (value: number) => {
       console.log("current value is :" + value);
   }
  1. Play the animation.
   // Play the animation.
   result.play();
  1. After the animation has finished executing, manually release the AnimatorResult object.
   // Release the animation object.
   result = undefined;

Using Frame Animation to Implement a Ball’s Parabolic Motion

  1. Import dependencies.
   import { AnimatorOptions, AnimatorResult } from '@kit.ArkUI';
  1. Define the component to be animated.
   Button()
     .width(60)
     .height(60)
     .translate({ x: this.translateX, y: this.translateY })
  1. Create an AnimatorResult Object in onPageShow.
   onPageShow(): void {
       // Create an animatorResult object.
       this.animatorOptions = this.getUIContext().createAnimator(options);
       this.animatorOptions.onFrame = (progress: number) => {
       this.translateX = progress;
       if (progress > this.topWidth && this.translateY < this.bottomHeight) {
          this.translateY = Math.pow(progress - this.topWidth, 2) * this.g;
       }
    }
    // Invoked when the animation is canceled.
    this.animatorOptions.onCancel = () => {
       this.animatorStatus = 'Canceled'
    }
    // Invoked when the animation finishes playing.
    this.animatorOptions.onFinish = () => {
       this.animatorStatus = 'Finished'
    }
    // Invoked when the animation repeats.
    this.animatorOptions.onRepeat = () => {
       console.log("Animation repeating");
    }
   }
  1. Define buttons for controlling the animation.
   Button('Play').onClick(() => {
     this.animatorOptions?.play();
     this.animatorStatus = 'Playing'
   }).width(80).height(35)
   Button("Reset").onClick(() => {
     this.translateX = 0;
     this.translateY = 0;
   }).width(80).height(35)
   Button("Pause").onClick(() => {
     this.animatorOptions?.pause();
     this.animatorStatus = 'Paused'
   }).width(80).height(35)
  1. Destroy the animation in the page’s onPageHide lifecycle callback to avoid memory leak. ts onPageHide(): void { this.animatorOptions = undefined; }

A complete example is as follows:

import { AnimatorOptions, AnimatorResult } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  @State animatorOptions: AnimatorResult|undefined = undefined;
  @State animatorStatus: string =' Created'
  begin: number = 0;
  end: number = 300
  topWidth: number = 150;
  bottomHeight: number = 100;
  g: number = 0.18
  animatorOption: AnimatorOptions = {
    duration: 4000,
    delay: 0,
    easing: 'linear',
    iterations: 1,
    fill: "forwards",
    direction: 'normal',
    begin: this.begin,
    end: this.end
  };
  @State translateX: number = 0;
  @State translateY: number = 0;

  onPageShow(): void {
    this.animatorOptions = this.getUIContext().createAnimator(this.animatorOption)
    this.animatorOptions.onFrame = (progress: number) => {
      this.translateX = progress;
      if (progress > this.topWidth && this.translateY < this.bottomHeight) {
        this.translateY = Math.pow(progress - this.topWidth, 2) * this.g;
      }
    }
    this.animatorOptions.onCancel = () => {
      this.animatorStatus = 'Canceled'
    }
    this.animatorOptions.onFinish = () => {
      this.animatorStatus = 'Finished'
    }
    this.animatorOptions.onRepeat = () => {
      console.log("Animation repeating");
    }
  }

  onPageHide(): void {
    this.animatorOptions = undefined;
  }

  build() {
    Column() {
      Column({ space: 30 }) {
        Button('Play').onClick(() => {
          this.animatorOptions?.play();
          this.animatorStatus = 'Playing';
        }).width(80).height(35)
        Button("Reset").onClick(() => {
          this.translateX = 0;
          this.translateY = 0;
        }).width(80).height(35)
        Button("Pause").onClick(() => {
          this.animatorOptions?.pause();
          this.animatorStatus = 'Paused';
        }).width(80).height(35)
      }.width("100%").height('25%')

      Stack() {
        Button()
          .width(60)
          .height(60)
          .translate({ x: this.translateX, y: this.translateY })
      }
      .width("100%")
      .height('45%')
      .align(Alignment.Start)

      Text("Current animation state: "+ this.animatorStatus)
    }.width("100%").height('100%')
  }
}

en-us_image_0000001599958466

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkUI

harmony 鸿蒙Atomic Service Full Screen Launch Component (FullScreenLaunchComponent)

harmony 鸿蒙Arc Button (ArcButton)

harmony 鸿蒙Animation Smoothing

harmony 鸿蒙Animation Overview

harmony 鸿蒙Implementing Property Animation

harmony 鸿蒙Property Animation Overview

harmony 鸿蒙Dialog Box Overview

harmony 鸿蒙Blur Effect

harmony 鸿蒙Color Effect

0  赞