<acronym id="s8ci2"><small id="s8ci2"></small></acronym>
<rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
<acronym id="s8ci2"></acronym>
<acronym id="s8ci2"><center id="s8ci2"></center></acronym>
0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

OpenHarmony實戰開發-如何實現組件動畫。

碼牛程序猿 ? 來源:jf_71304091 ? 作者:jf_71304091 ? 2024-04-28 15:49 ? 次閱讀

ArkUI為組件提供了通用的屬性動畫和轉場動畫能力的同時,還為一些組件提供了默認的動畫效果。例如,List的滑動動效,Button的點擊動效,是組件自帶的默認動畫效果。在組件默認動畫效果的基礎上,開發者還可以通過屬性動畫和轉場動畫對容器組件內的子組件動效進行定制。

使用組件默認動畫

組件默認動效具備以下功能:

  • 提示用戶當前狀態,例如用戶點擊Button組件時,Button組件默認變灰,用戶即確定完成選中操作。
  • 提升界面精致程度和生動性。
  • 減少開發者工作量,例如列表滑動組件自帶滑動動效,開發者直接調用即可。

更多效果,可以參考組件說明。

示例代碼和效果如下。

@Entry
@Component
struct ComponentDemo {
  build() {
    Row() {
      Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
        .select(true)
        .shape(CheckBoxShape.CIRCLE)
        .size({ width: 50, height: 50 })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
ts

打造組件定制化動效

部分組件支持通過屬性動畫和轉場動畫自定義組件子Item的動效,實現定制化動畫效果。例如,Scroll組件中可對各個子組件在滑動時的動畫效果進行定制。

  • 在滑動或者點擊操作時通過改變各個Scroll子組件的仿射屬性來實現各種效果。
  • 如果要在滑動過程中定制動效,可在滑動回調onScroll中監控滑動距離,并計算每個組件的仿射屬性。也可以自己定義手勢,通過手勢監控位置,手動調用ScrollTo改變滑動位置。
  • 在滑動回調onScrollStop或手勢結束回調中對滑動的最終位置進行微調。

定制Scroll組件滑動動效示例代碼和效果如下。

import curves from '@ohos.curves';
import window from '@ohos.window';
import display from '@ohos.display';
import mediaquery from '@ohos.mediaquery';
import UIAbility from '@ohos.app.ability.UIAbility';

export default class GlobalContext extends AppStorage{
  static mainWin: window.Window|undefined = undefined;
  static mainWindowSize:window.Size|undefined = undefined;
}
/**
 * 窗口、屏幕相關信息管理類
 */
export class WindowManager {
  private static instance: WindowManager|null = null;
  private displayInfo: display.Display|null = null;
  private orientationListener = mediaquery.matchMediaSync('(orientation: landscape)');

  constructor() {
    this.orientationListener.on('change', (mediaQueryResult: mediaquery.MediaQueryResult) = > { this.onPortrait(mediaQueryResult) })
    this.loadDisplayInfo()
  }

  /**
   * 設置主window窗口
   * @param win 當前app窗口
   */
  setMainWin(win: window.Window) {
    if (win == null) {
      return
    }
    GlobalContext.mainWin = win;
    win.on("windowSizeChange", (data: window.Size) = > {
      if (GlobalContext.mainWindowSize == undefined || GlobalContext.mainWindowSize == null) {
        GlobalContext.mainWindowSize = data;
      } else {
        if (GlobalContext.mainWindowSize.width == data.width && GlobalContext.mainWindowSize.height == data.height) {
          return
        }
        GlobalContext.mainWindowSize = data;
      }

      let winWidth = this.getMainWindowWidth();
      AppStorage.setOrCreate< number >('mainWinWidth', winWidth)
      let winHeight = this.getMainWindowHeight();
      AppStorage.setOrCreate< number >('mainWinHeight', winHeight)
      let context:UIAbility = new UIAbility()
      context.context.eventHub.emit("windowSizeChange", winWidth, winHeight)
    })
  }

  static getInstance(): WindowManager {
    if (WindowManager.instance == null) {
      WindowManager.instance = new WindowManager();
    }
    return WindowManager.instance
  }

  private onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) {
    if (mediaQueryResult.matches == AppStorage.get< boolean >('isLandscape')) {
      return
    }
    AppStorage.setOrCreate< boolean >('isLandscape', mediaQueryResult.matches)
    this.loadDisplayInfo()
  }

  /**
   * 切換屏幕方向
   * @param ori 常量枚舉值:window.Orientation
   */
  changeOrientation(ori: window.Orientation) {
    if (GlobalContext.mainWin != null) {
      GlobalContext.mainWin.setPreferredOrientation(ori)
    }
  }

  private loadDisplayInfo() {
    this.displayInfo = display.getDefaultDisplaySync()
    AppStorage.setOrCreate< number >('displayWidth', this.getDisplayWidth())
    AppStorage.setOrCreate< number >('displayHeight', this.getDisplayHeight())
  }

  /**
   * 獲取main窗口寬度,單位vp
   */
  getMainWindowWidth(): number {
    return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.width) : 0
  }

  /**
   * 獲取main窗口高度,單位vp
   */
  getMainWindowHeight(): number {
    return GlobalContext.mainWindowSize != null ? px2vp(GlobalContext.mainWindowSize.height) : 0
  }

  /**
   * 獲取屏幕寬度,單位vp
   */
  getDisplayWidth(): number {
    return this.displayInfo != null ? px2vp(this.displayInfo.width) : 0
  }

  /**
   * 獲取屏幕高度,單位vp
   */
  getDisplayHeight(): number {
    return this.displayInfo != null ? px2vp(this.displayInfo.height) : 0
  }

  /**
   * 釋放資源
   */
  release() {
    if (this.orientationListener) {
      this.orientationListener.off('change', (mediaQueryResult: mediaquery.MediaQueryResult) = > { this.onPortrait(mediaQueryResult)})
    }
    if (GlobalContext.mainWin != null) {
      GlobalContext.mainWin.off('windowSizeChange')
    }
    WindowManager.instance = null;
  }
}

/**
 * 封裝任務卡片信息數據類
 */
export class TaskData {
  bgColor: Color | string | Resource = Color.White;
  index: number = 0;
  taskInfo: string = 'music';

  constructor(bgColor: Color | string | Resource, index: number, taskInfo: string) {
    this.bgColor = bgColor;
    this.index = index;
    this.taskInfo = taskInfo;
  }
}

export const taskDataArr: Array< TaskData > =
  [
    new TaskData('#317AF7', 0, 'music'),
    new TaskData('#D94838', 1, 'mall'),
    new TaskData('#DB6B42 ', 2, 'photos'),
    new TaskData('#5BA854', 3, 'setting'),
    new TaskData('#317AF7', 4, 'call'),
    new TaskData('#D94838', 5, 'music'),
    new TaskData('#DB6B42', 6, 'mall'),
    new TaskData('#5BA854', 7, 'photos'),
    new TaskData('#D94838', 8, 'setting'),
    new TaskData('#DB6B42', 9, 'call'),
    new TaskData('#5BA854', 10, 'music')

  ];

@Entry
@Component
export struct TaskSwitchMainPage {
  displayWidth: number = WindowManager.getInstance().getDisplayWidth();
  scroller: Scroller = new Scroller();
  cardSpace: number = 0; // 卡片間距
  cardWidth: number = this.displayWidth / 2 - this.cardSpace / 2; // 卡片寬度
  cardHeight: number = 400; // 卡片高度
  cardPosition: Array< number > = []; // 卡片初始位置
  clickIndex: boolean = false;
  @State taskViewOffsetX: number = 0;
  @State cardOffset: number = this.displayWidth / 4;
  lastCardOffset: number = this.cardOffset;
  startTime: number|undefined=undefined

  // 每個卡片初始位置
  aboutToAppear() {
    for (let i = 0; i < taskDataArr.length; i++) {
      this.cardPosition[i] = i * (this.cardWidth + this.cardSpace);
    }
  }

  // 每個卡片位置
  getProgress(index: number): number {
    let progress = (this.cardOffset + this.cardPosition[index] - this.taskViewOffsetX + this.cardWidth / 2) / this.displayWidth;
    return progress
  }

  build() {
    Stack({ alignContent: Alignment.Bottom }) {
      // 背景
      Column()
        .width('100%')
        .height('100%')
        .backgroundColor(0xF0F0F0)

      // 滑動組件
      Scroll(this.scroller) {
        Row({ space: this.cardSpace }) {
          ForEach(taskDataArr, (item:TaskData, index) = > {
            Column()
              .width(this.cardWidth)
              .height(this.cardHeight)
              .backgroundColor(item.bgColor)
              .borderStyle(BorderStyle.Solid)
              .borderWidth(1)
              .borderColor(0xAFEEEE)
              .borderRadius(15)
                // 計算子組件的仿射屬性
              .scale((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ?
                {
                  x: 1.1 - Math.abs(0.5 - this.getProgress(index)),
                  y: 1.1 - Math.abs(0.5 - this.getProgress(index))
                } :
                { x: 1, y: 1 })
              .animation({ curve: Curve.Smooth })
                // 滑動動畫
              .translate({ x: this.cardOffset })
              .animation({ curve: curves.springMotion() })
              .zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1)
          }, (item:TaskData) = > item.toString())
        }
        .width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1))
        .height('100%')
      }
      .gesture(
        GestureGroup(GestureMode.Parallel,
          PanGesture({ direction: PanDirection.Horizontal, distance: 5 })
            .onActionStart((event: GestureEvent|undefined) = > {
              if(event){
                this.startTime = event.timestamp;
              }
            })
            .onActionUpdate((event: GestureEvent|undefined) = > {
              if(event){
                this.cardOffset = this.lastCardOffset + event.offsetX;
              }
            })
            .onActionEnd((event: GestureEvent|undefined) = > {
              if(event){
                let time = 0
                if(this.startTime){
                  time = event.timestamp - this.startTime;
                }
                let speed = event.offsetX / (time / 1000000000);
                let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1);

                this.cardOffset += moveX;
                // 左滑大于最右側位置
                let cardOffsetMax = -(taskDataArr.length - 1) * (this.displayWidth / 2);
                if (this.cardOffset < cardOffsetMax) {
                  this.cardOffset = cardOffsetMax;
                }
                // 右滑大于最左側位置
                if (this.cardOffset > this.displayWidth / 4) {
                  this.cardOffset = this.displayWidth / 4;
                }

                // 左右滑動距離不滿足/滿足切換關系時,補位/退回
                let remainMargin = this.cardOffset % (this.displayWidth / 2);
                if (remainMargin < 0) {
                  remainMargin = this.cardOffset % (this.displayWidth / 2) + this.displayWidth / 2;
                }
                if (remainMargin <= this.displayWidth / 4) {
                  this.cardOffset += this.displayWidth / 4 - remainMargin;
                } else {
                  this.cardOffset -= this.displayWidth / 4 - (this.displayWidth / 2 - remainMargin);
                }

                // 記錄本次滑動偏移量
                this.lastCardOffset = this.cardOffset;
              }
            })
        ), GestureMask.IgnoreInternal)
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)

      // 滑動到首尾位置
      Button('Move to first/last')
        .backgroundColor(0x888888)
        .margin({ bottom: 30 })
        .onClick(() = > {
          this.clickIndex = !this.clickIndex;

          if (this.clickIndex) {
            this.cardOffset = this.displayWidth / 4;
          } else {
            this.cardOffset = this.displayWidth / 4 - (taskDataArr.length - 1) * this.displayWidth / 2;
          }
          this.lastCardOffset = this.cardOffset;
        })
    }
    .width('100%')
    .height('100%')
  }
}
ts

審核編輯 黃宇

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 組件
    +關注

    關注

    1

    文章

    367

    瀏覽量

    17638
  • 鴻蒙
    +關注

    關注

    55

    文章

    1919

    瀏覽量

    42194
  • OpenHarmony
    +關注

    關注

    24

    文章

    3442

    瀏覽量

    15279
收藏 人收藏

    評論

    相關推薦

    [OpenHarmony北向應用開發] 做一個 loading加載動畫

    - 本篇文章介紹了如何實現一個簡單的loading加載動畫,并且在提供了一個demo工程供讀者下載學習。 - loading加載動畫demo下載地址: https://gitee.com
    的頭像 發表于 04-20 11:29 ?1507次閱讀
    [<b class='flag-5'>OpenHarmony</b>北向應用<b class='flag-5'>開發</b>] 做一個 loading加載<b class='flag-5'>動畫</b>

    鴻蒙開發OpenHarmony組件復用案例

    和響應速度。 在OpenHarmony應用開發時,自定義組件被@Reusable裝飾器修飾時表示該自定義組件可以復用。在父自定義組件下創建的
    發表于 01-15 17:37

    OpenHarmony實戰開發-如何實現動畫

    你們的 『點贊和評論』,才是我創造的動力。 關注小編,同時可以期待后續文章ing?,不定期分享原創知識。 更多鴻蒙最新技術知識點,請關注作者博客:鴻蒙實戰經驗分享:鴻蒙基礎入門開發寶典! (qq.com)**
    發表于 05-06 14:11

    OpenHarmony實戰開發-如何實現窗口開發概述

    操作系統而言,窗口模塊提供了不同應用界面的組織管理邏輯。 窗口模塊的用途 在OpenHarmony中,窗口模塊主要負責以下職責: 提供應用和系統界面的窗口對象。 應用開發者通過窗口加載UI界面,實現界面
    發表于 05-06 14:29

    HarmonyOS Lottie組件,讓動畫繪制更簡單

    了豐富的API,讓開發者能輕松控制動畫,大大提高了開發效率。 二、Lottie實戰 通過上文對Lottie的介紹,相信很多小伙伴已經感受到了Lottie
    發表于 02-22 14:55

    OpenHarmony標準設備應用開發筆記匯總

    如何在標準設備上運行一個最簡單的 OpenHarmony 程序。2、如何在OpenHarmony實現音樂的播放本章是 OpenHarmony 標準設備應用
    發表于 03-28 14:19

    OpenHarmony標準設備應用開發(二)——布局、動畫與音樂

    節的基礎上,學到更多 ArkUI 組件和布局在 OpenHarmony 中的應用,以及如何在自己的應用中實現顯示動畫的效果。代碼鏈接:https://gitee.com/
    發表于 04-07 17:09

    OpenHarmony有氧拳擊之應用端開發

    變化的動畫,便很適合使用屬性動畫實現。屬性動畫是指組件的通用屬性發生變化時,會根據開始狀態和通用屬性改變后的狀態作為
    發表于 10-09 15:19

    OpenHarmony數據轉碼應用開發實戰(下)

    OpenHarmony數據轉碼應用開發實戰(中)》我們講述了核心解轉碼工具包的實現,以及UI組件數據綁定,那么接下來將講述項目的國際化適配
    發表于 11-10 09:31

    HarmonyOS/OpenHarmony應用開發-屬性動畫

    組件的某些通用屬性變化時,可以通過屬性動畫實現漸變過渡效果,提升用戶體驗。支持的屬性包括width、height、backgroundColor、opacity、scale、rotate
    發表于 01-03 10:51

    OpenHarmony應用開發—ArkUI組件集合

    頁面 接口參考:@ohos.curves, @ohos.router 顯示動畫 用到全局組件TitleBar,IntroductionTitle實現頁面 接口參考:animateTo 屬性
    發表于 09-22 14:56

    openharmony第三方組件適配移植的動畫實現

    項目介紹 項目名稱:CanAnimation 所屬系列:openharmony的第三方組件適配移植 功能:使用openharmony屬性動畫寫的一個庫,可組建
    發表于 04-02 11:30 ?3次下載

    OpenHarmony技術論壇:傳統動畫實現的不足

    OpenHarmony技術論壇:流暢動畫可傳統動畫實現的不足。
    的頭像 發表于 04-25 14:21 ?833次閱讀
    <b class='flag-5'>OpenHarmony</b>技術論壇:傳統<b class='flag-5'>動畫</b><b class='flag-5'>實現</b>的不足

    如何在OpenHarmony實現逐幀動畫?

    逐幀動畫是常見的一種動畫呈現形式,本例就為大家介紹如何通過 translate(),setInterval(),clearAllInterval() 等方法實現逐幀動畫。
    的頭像 發表于 06-18 15:14 ?540次閱讀
    如何在<b class='flag-5'>OpenHarmony</b>上<b class='flag-5'>實現</b>逐幀<b class='flag-5'>動畫</b>?

    OpenHarmony輕量系統書籍推薦《OpenHarmony輕量設備開發理論與實戰

    最近大家問的智能家居套件方面有沒有可以參考的資料,這里給大家統一回復一下 推薦大家可以看這本書 《OpenHarmony輕量設備開發理論與實戰》 本書系統地講授OpenHarmony
    的頭像 發表于 07-20 12:43 ?757次閱讀
    亚洲欧美日韩精品久久_久久精品AⅤ无码中文_日本中文字幕有码在线播放_亚洲视频高清不卡在线观看
    <acronym id="s8ci2"><small id="s8ci2"></small></acronym>
    <rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
    <acronym id="s8ci2"></acronym>
    <acronym id="s8ci2"><center id="s8ci2"></center></acronym>