鴻蒙banner輪播堆疊效果

完整代碼 : https://github.com/dazeGitHub/TestHarmonyBanner

定義組件 SwiperComponentHalfFold :

import { SwiperData } from '../model/SwiperData';
import Logger from '../utils/Logger';

/**
 * 層疊輪播圖組件
 * 是 SwiperComponent 的修改版, 只顯示右側(cè)的折疊部分
 */
@Component
export struct SwiperComponentHalfFold {
  @State currentIndex: number = 0;
  @State swiperData: SwiperData[] = [
    new SwiperData($r("app.media.mp_chart"), 'MpChart圖表實(shí)現(xiàn)案例'),
    new SwiperData($r("app.media.lottie"), 'Lottie動(dòng)畫'),
    new SwiperData($r("app.media.component_tack"), '組件堆疊'),
    new SwiperData($r("app.media.ic_swiper1"), '輪播1'),
    new SwiperData($r("app.media.ic_swiper2"), '輪播2'),
    new SwiperData($r("app.media.ic_swiper3"), '輪播3'),
  ];
  private halfCount: number = Math.floor(6 / 2);  //半數(shù) = 總數(shù) / 2
  private manualSlidingDuration: number = 800;    //手動(dòng)滑動(dòng)時(shí)長(zhǎng)
  private automaticSlidingDuration: number = 300;
  private automaticSwitchTime: number = 5000;
  private offsetXValue = 15;
  @State swiperInterval: number = 0

  aboutToAppear(): void {
    this.currentIndex = this.halfCount;
    this.swiperInterval = setInterval(() => {
      this.startAnimation(true, this.manualSlidingDuration);
    }, this.automaticSwitchTime);
  }

  /**
   * 獲取圖片系數(shù)
   * @param index:索引值
   * @returns
   */
  getImgCoefficients(index: number): number {
    const coefficient: number = this.currentIndex - index; // 計(jì)算圖片左右位置
    const tempCoefficient: number = Math.abs(coefficient);
    if (tempCoefficient <= this.halfCount) {
      return coefficient;
    }
    const dataLength: number = this.swiperData.length;
    let tempOffset: number = dataLength - tempCoefficient; // 判斷圖片位于左右層級(jí)位置
    if (tempOffset <= this.halfCount) { //如果在左側(cè)
      if (coefficient > 0) {
        return -tempOffset;
      }
      return tempOffset;
    }
    return 0;
  }

  /**
   * 計(jì)算偏移量
   * @param index:索引值
   * @returns
   */
  getOffSetX(index: number): number {
    const offsetIndex: number = this.getImgCoefficients(index);
    const tempOffset: number = Math.abs(offsetIndex);
    let offsetX: number = 0;
    if (tempOffset === 1) {
      // 根據(jù)圖片層級(jí)系數(shù)來決定左右偏移量
      offsetX = -15 * offsetIndex;
    }
    if (tempOffset === 2) {
      // 根據(jù)圖片層級(jí)系數(shù)來決定左右偏移量
      offsetX = -this.offsetXValue * offsetIndex;
    }
    Logger.info("TAG", "index = " + index + " offsetX = " + offsetX)
    return offsetX;
  }

  // 性能:顯式動(dòng)畫(https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/ts-explicit-animation-0000001478341181-V2)
  startAnimation(isLeft: boolean, duration: number): void {
    animateTo({
      duration: duration,
    }, () => {
      const dataLength: number = this.swiperData.length;
      const tempIndex: number = isLeft ? this.currentIndex + 1 : this.currentIndex - 1 + dataLength;
      this.currentIndex = tempIndex % dataLength;
    })
  }

  build() {
    Column() {
      Stack() {
        // LazyForEach必須在容器組件內(nèi)使用,僅有List粉楚、Grid恒水、Swiper以及WaterFlow組件支持?jǐn)?shù)據(jù)懶加載,其他組件仍然是一次性加載所有的數(shù)據(jù)梧乘。
        ForEach(this.swiperData, (item: SwiperData, index: number) => {
          Stack({ alignContent: Alignment.BottomStart }) {
            Image(item.imageSrc)
              .objectFit(ImageFit.Cover)
              .width('100%')
              .height('100%')
              .borderRadius($r('app.string.main_page_top_borderRadius'))
            // 輪播圖底部蒙層 必定在上方
            Stack() {
              Column() {
              }
              .width('100%')
              .height('100%')
              .backgroundColor(Color.Black)
              .opacity(0.3)
              .borderRadius({
                topLeft: 0,
                topRight: 0,
                bottomLeft: $r('app.string.main_page_top_borderRadius'),
                bottomRight: $r('app.string.main_page_top_borderRadius')
              })

              Text(item.name)
                .width('100%')
                .height('100%')
                .fontSize(16)
                .fontColor(Color.White)
                .textAlign(TextAlign.Start)
                .padding($r('app.string.main_page_padding5'))
            }
            .height($r('app.string.bottom_title_height'))
          }
          .backgroundColor(Color.White)
          .borderRadius(8)
          .offset({
            x: this.getOffSetX(index),
            y: 0
          })
          .blur(index !== this.currentIndex ? 12 : 0)
          // TODO: 知識(shí)點(diǎn):通過animateTo實(shí)現(xiàn)動(dòng)畫并且同時(shí)改變currentIndex數(shù)據(jù)中間值來判斷組件zIndex實(shí)現(xiàn)切換動(dòng)畫
          .zIndex(index !== this.currentIndex && this.getImgCoefficients(index) === 0 ?
            0 : 2 - Math.abs(this.getImgCoefficients(index)))
          .width($r('app.string.swiper_stack_width'))
          // .height(index !== this.currentIndex ? $r('app.string.swiper_stack_height1') : $r('app.string.swiper_stack_height2'))
          .height(
            index === this.currentIndex ?
              $r("app.string.swiper_stack_height1")
              : ((index === this.currentIndex - 1 || index === this.currentIndex + 1) ?
                $r("app.string.swiper_stack_height2") :
                $r("app.string.swiper_stack_height3"))
          )
          .onClick(() => {
            // 點(diǎn)擊輪播圖Item時(shí)绊序,根據(jù)點(diǎn)擊的模塊信息,將頁面放入路由棧
            // DynamicsRouter.push(item.routerInfo, item.param);
          })
        })
      }
      .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
        clearInterval(this.swiperInterval);
        if (isVisible && currentRatio >= 1.0) {
          this.swiperInterval = setInterval(() => {
            this.startAnimation(true, this.manualSlidingDuration);
          }, this.automaticSwitchTime)
        }

        if (!isVisible && currentRatio <= 0.0) {
          clearInterval(this.swiperInterval);
        }
      })
      //高度必須和 app.string.swiper_stack_height1 相同
      .height($r('app.string.swiper_stack_height1'))
      .width('100%')
      .gesture(
        PanGesture({ direction: PanDirection.Horizontal })
          .onActionStart((event: GestureEvent) => {
            clearInterval(this.swiperInterval);
            this.startAnimation(event.offsetX < 0, this.automaticSlidingDuration);
          })
          .onActionEnd(() => {
            this.swiperInterval = setInterval(() => {
              this.startAnimation(true, this.manualSlidingDuration);
            }, this.automaticSwitchTime);
          })
      )
      .alignContent(Alignment.Start)
      .backgroundColor($r("app.color.green"))
      .clip(true) //裁剪超出 banner 左側(cè)的層疊部分
      .margin({left: "100vp"})
      // .margin({left: -this.offsetXValue * 2}) //整體左移動(dòng)兩個(gè)位移

      //底部指示器
      Row({ space: 10 }) {
        ForEach(this.swiperData, (item: SwiperData, index: number) => {
          Ellipse(index !== this.currentIndex ? { width: 8, height: 8 } : { width: 10, height: 8 })
            .fill(index !== this.currentIndex ? Color.Black : Color.Red)
            .fillOpacity(0.6)
        })
      }
      .margin({ top: 12 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r("app.color.blue"))
    .justifyContent(FlexAlign.Start)
  }
}

使用組件 SwiperComponentHalfFold :

import { SwiperComponentHalfFold } from '../components/SwiperComponentHalfFold'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        // SwiperComponent()
        // SwiperComponentThreeEle()
        SwiperComponentHalfFold()
      }
      .width('100%')
    }
    .height('100%')
  }
}

運(yùn)行結(jié)果如下 :

Snipaste_2024-04-13_15-34-29.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末孔飒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子艰争,更是在濱河造成了極大的恐慌坏瞄,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蝴蜓,警方通過查閱死者的電腦和手機(jī)福青,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來莺葫,“玉大人,你說我怎么就攤上這事∨婪叮” “怎么了?”我有些...
    開封第一講書人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵弱匪,是天一觀的道長(zhǎng)青瀑。 經(jīng)常有香客問我,道長(zhǎng)萧诫,這世上最難降的妖魔是什么斥难? 我笑而不...
    開封第一講書人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮帘饶,結(jié)果婚禮上哑诊,老公的妹妹穿的比我還像新娘。我一直安慰自己及刻,他們只是感情好镀裤,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開白布穷当。 她就那樣靜靜地躺著,像睡著了一般淹禾。 火紅的嫁衣襯著肌膚如雪馁菜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,255評(píng)論 1 308
  • 那天铃岔,我揣著相機(jī)與錄音汪疮,去河邊找鬼。 笑死毁习,一個(gè)胖子當(dāng)著我的面吹牛智嚷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播纺且,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼盏道,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了载碌?” 一聲冷哼從身側(cè)響起猜嘱,我...
    開封第一講書人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎嫁艇,沒想到半個(gè)月后朗伶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡步咪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年论皆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猾漫。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡点晴,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出悯周,到底是詐尸還是另有隱情粒督,我是刑警寧澤,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布队橙,位于F島的核電站坠陈,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏捐康。R本人自食惡果不足惜仇矾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望解总。 院中可真熱鬧贮匕,春花似錦、人聲如沸花枫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至敦锌,卻和暖如春馒疹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背乙墙。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來泰國打工颖变, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人听想。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓腥刹,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親汉买。 傳聞我的和親對(duì)象是個(gè)殘疾皇子衔峰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359