鸿蒙应用开发-做一个随机转盘

使用鸿蒙三方库mpchart 可以很方便地做一个滚动转盘,可以做随机选择转盘中的任一项。

实现效果如下图所示:

实现代码如下:

import {
  ColorTemplate,
  JArrayList,
  MPPointF,
  PieChart,
  PieChartModel,
  PieData,
  PieDataSet,
  PieEntry
} from '@ohos/mpchart';
import animator, { AnimatorOptions, AnimatorResult } from '@ohos.animator';

@Entry
@Component
export default struct RoulettePage {
  model: PieChartModel = new PieChartModel();
  private animatorResult: AnimatorResult | null = null
  @State chooseText: string = '请选择';
  @State onePartAngle: number = 0;
  @State count: number = 8;
  @State currentIndex: number = 0;
  protected parties: string[] = [
    "黄焖鸡", "肯德基", "小炒肉", "螺蛳粉", "干炒牛河", "钵钵鸡", "重庆小碗面", "衡阳卤粉", "南昌拌粉"
  ];

  aboutToAppear(): void {
    this.init();
  }

  build() {
    Column() {
      Text('今天吃什么?').fontSize(24)
        .margin({bottom: 20})
      Text(this.chooseText).fontSize(28)
      Text('▼').fontSize(26).fontWeight(FontWeight.Bolder)
      Stack() {
        PieChart({ model: this.model })
          .width('90%')
          .aspectRatio(1)

        Button('开始滚动')
          .onClick(() => {
            this.startGun();
          }).alignSelf(ItemAlign.Center).padding(15).borderRadius(200).backgroundColor(Color.Orange)
      }
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }

  init() {
    this.model.getDescription()?.setEnabled(false);

    this.model.setDrawHoleEnabled(false);
    this.model.getLegend()?.setEnabled(false);

    this.model.disableScroll();
    this.model.setRotationEnabled(true);
    this.model.setHighlightPerTapEnabled(true);
    this.model.setEntryLabelTextSize(23)
    this.model.setTouchEnabled(false);

    this.setData(10);
  }

  // 初始化饼状图数据
  private async setData(range: number): Promise {
    let entries: JArrayList = new JArrayList();

    // NOTE: The order of the entries when being added to the entries array determines their position around the center of
    // the chart.
    for (let i = 0; i < this.count; i++) {
      entries.add(new PieEntry(range,
        this.parties[i % this.parties.length]));
    }

    let dataSet: PieDataSet = new PieDataSet(entries, "Election Results");
    dataSet.setSliceSpace(1);
    dataSet.setIconsOffset(new MPPointF(0, 40));
    dataSet.setSelectionShift(5);
    dataSet.setValueTextColor(Color.White);
    dataSet.setValueTextColor(25);
    dataSet.setDrawValues(false);

    // add a lot of colors
    let colors: JArrayList = new JArrayList();
    for (let index = 0; index < ColorTemplate.COLORFUL_COLORS.length; index++) {
      colors.add(ColorTemplate.COLORFUL_COLORS[index]);
    }

    colors.add(ColorTemplate.getHoloBlue());
    dataSet.setColorsByList(colors);
    let data: PieData = new PieData(dataSet);
    this.onePartAngle = 360 / this.count;
    this.model.setRotationAngle(-90 - this.onePartAngle / 2);
    this.model.setData(data);
  }

  getCurrentText(num: number): string {
    let nowIndex = this.currentIndex - num;
    if (nowIndex < 0) {
      nowIndex = this.count + nowIndex;
    }
    this.currentIndex = nowIndex;
    return (this.parties[this.currentIndex]);
  }

  startGun() {
    this.chooseText = '选取中';
    let currentAngle = this.model.getRotationAngle();
    let randomIndex: number = Math.floor(Math.random() * this.count);

    console.log("xxxx=" + randomIndex);
    let end = 7200 + currentAngle + randomIndex * this.onePartAngle;
    let chooseText = this.getCurrentText(randomIndex);
    let options: AnimatorOptions = {
      duration: 8000,
      easing: "ease",
      delay: 0,
      fill: "forwards",
      direction: "normal",
      begin: currentAngle,
      end: end,
      iterations: 1
    };
    this.animatorResult = animator.create(options)
    this.animatorResult.onframe = (value) => {
      this.model.setRotationAngle(value);
      this.model.invalidate();
    }
    this.animatorResult.onfinish = () => {
      this.chooseText = chooseText;
    }
    this.animatorResult.play();
  }
}

实现方法比较简单,就不细讲了,如果可以的话,点击下载支持一下:

https://download.csdn.net/download/liuhaikang/89509449

你可能感兴趣的:(鸿蒙应用开发,harmonyos,华为)