HarmonyOS implements static and dynamic data visualization charts

1. Sample introduction

This Codelab is based on the switch component and chart component to implement line graphs, proportion graphs, and histograms, and switches the dynamic and static display of chart component data through switch. The following functions are required:

  1. Implement static data visualization charts.
  2. Turn on the switch to switch from static chart to dynamic visual chart

Related concepts

  • switch component : switch selector, which turns a certain function on or off through a switch.
  • Chart component : Chart component, used to present line chart, proportion chart, and bar chart interface.

Complete example

gitee source code address

2. Environment setup

We first need to complete the establishment of the HarmonyOS development environment. Please refer to the following steps.

Software requirements

Hardware requirements

  • Device type: Huawei mobile phone or Huawei mobile phone device simulator running on DevEco Studio.
  • HarmonyOS system: 3.1.0 Developer Release and above.

Environment build

  1. Install DevEco Studio. For details, please refer to Download and Install Software .
  2. Set up the DevEco Studio development environment. The DevEco Studio development environment depends on the network environment. You need to be connected to the network to ensure the normal use of the tool. You can configure the development environment according to the following two situations: If you can directly access the Internet, you only need to download the HarmonyOS SDK operate.
    1. If the network cannot directly access the Internet and needs to be accessed through a proxy server, please refer to Configuring the Development Environment .
  3. Developers can refer to the following link to complete the relevant configuration of device debugging:

3. Interpretation of code structure

This Codelab only explains the core code. For the complete code, we will provide it in the source code download or gitee.

├──entry/src/main/js	     // 代码区
│  └──MainAbility
│     ├──common
│     │  └──images           // 图片资源
│     ├──i18n		     // 国际化中英文
│     │  ├──en-US.json			
│     │  └──zh-CN.json			
│     ├──pages
│     │  └──index
│     │     ├──index.css     // 首页样式文件	
│     │     ├──index.hml     // 首页布局文件
│     │     └──index.js      // 首页业务处理文件
│     └──app.js              // 程序入口
└──entry/src/main/resources  // 应用资源目录

4. Build the main interface

This chapter will introduce the implementation of the application main page. The page is divided into two parts from top to bottom:

  1. Use the switch component to implement a switch button to control the dynamic and static display of chart component data.
  2. Use the chart component to implement line charts, proportion charts, and bar charts in sequence.

This application uses the div component as the outer container, and nests basic components such as text, chart, and switch to jointly present the effect of graphic and text display.

<!-- index.hml -->
<div class="container">
    <!-- 自定义标题组件 -->
    <div class="switch-block">
        <text class="title">Switch_Chart</text>
        <text class="switch-info">{
       
       { $t('strings.switchInfo') }}</text>
        <!-- switch按钮组件 -->
        <switch onchange="change"></switch>
    </div>
</div>

In line graphs, lineOps is used to set line graph parameters, including curve style, endpoint style, etc. lineData is the data of the line graph.

<!-- index.hml -->
<div class="container">
    ....
    <!-- 线形图组件 -->
    <div class="chart-block">
        <stack class="stack-center">
            <image class="background-image" src="common/images/bg_png_line.png"></image>
            <!-- 线形图 -->
            <chart class="chart-data" type="line" ref="linechart" options="{
       
       { lineOps }}"
              datasets="{
       
       { lineData }}">
            </chart>
        </stack>
        <!-- 线形图标题 -->
        <text class="text-vertical">{
       
       { $t('strings.lineTitle') }}</text>
    </div>
</div>

Compared with the line chart, the proportion chart adds a custom legend. Among them, rainBowData is the data of the proportion map.

<!-- index.hml -->
<div class="container">
    ....
    <!-- 占比图组件 -->
    <div class="gauge-block">
        <div class='flex-row-center full-size'>
            <stack class="flex-row-center rainbow-size">
                <!-- 占比图组件 -->
                <chart class="data-gauge" type="rainbow" segments="{
       
       { rainBowData }}" effects="true"
                        animationduration="2000"></chart>
                ...
            </stack>
            <div class='flex-column'>
                <!-- 自定义图例 -->    
                <div class="chart-legend-item">
                    <div class="chart-legend-icon rainbow-color-photo"></div>
                    <text class="chart-legend-text">{
       
       { this.$t('strings.legendPhoto') }64GB</text>
                </div>
                ....
            </div>
        </div>
        <!-- 占比图标题 -->
        <text class="text-vertical">{
       
       { $t('strings.rainBowTitle') }}</text>
    </div>
</div>

In the histogram, barOps is used to set the histogram parameters, and barData is the histogram data.

<!-- index.hml -->
<div class="container">
    <div class="bar-block">
        <div class="flex-column full-size">
            <!-- 自定义图例 -->
            ...
            <stack class="full-size bar-height">
                <image class="background-image" src="common/images/bg_png_bar.png"></image>
                <!-- 柱状图 -->
                <chart class="data-bar" type="bar" id="bar-chart1" options="{
       
       { barOps }}" 
                  datasets="{
       
       { barData }}">  
                </chart>
            </stack>
        </div>
        <!-- 柱状图标题 -->
        <text class="text-vertical">{
       
       { $t('strings.barTitle') }}</text>
    </div>
</div>

5. Dynamically display data

In the previous chapter, we explained how to implement the switch button using the switch component. Next, we implemented the click event of the switch component. Set the chart component to be displayed statically or dynamically in the callback method. When static, the chart component displays static data. When dynamic, the interval timer is used to dynamically generate and display random data.

// index.js
export default {
       
       
  ...
  // switch按钮点击事件的回调方法
  change(event) {
       
       
    if (event.checked) {
       
       
      // 线形图、柱状图数据定时器
      this.interval = setInterval(() => {
       
       
        // 更新线形图数据
        this.changeLine(); 
        // 更新柱状图数据
        this.changeBar(); 
      }, 1000);
      // 占比图数据定时器
      this.rainbowInterval = setInterval(() => {
       
       
        // 更新占比图数据
        this.changeGauge(); 
      }, 3000);
    } else {
       
       
      clearInterval(this.interval);
      clearInterval(this.rainbowInterval);
    }
  }
}

Implement the changeLine method to update the line chart data. Iterate through all data, regenerate random numbers and set the data, shape, size and color of each point, and finally reassign lineData.

// index.js
export default {
       
       
  ...
  // 更新线形图数据
  changeLine() {
       
       
    const dataArray = [];
    for (let i = 0; i < this.dataLength; i++) {
       
       
      const nowValue = Math.floor(Math.random() * CommonConstants.LINE_RANDOM_MAX + 1);
      const obj = {
       
       
        // y轴的值
        'value': nowValue,
        'pointStyle': {
       
       
          // 点的形状
          'shape': 'circle',
          'size': CommonConstants.LINE_POINT_SIZE,
          'fillColor': '#FFFFFF',
          'strokeColor': '#0A59F7'
        }
      };
      dataArray.push(obj);
    }
    this.lineData = [
      {
       
       
        // 曲线颜色
        strokeColor: '#0A59F7',
        // 渐变填充颜色
        fillColor: '#0A59F7', 
        data: dataArray,
        gradient: true
      }
    ];
  }
}

Implement the changeGauge method to update the proportion graph data, increasing the data by 5% every three seconds.

// index.js
export default {
       
       
  ...
  // 更新线形图数据
  changeLine() {
       
       
    const dataArray = [];
    for (let i = 0; i < this.dataLength; i++) {
       
       
      const nowValue = Math.floor(Math.random() * CommonConstants.LINE_RANDOM_MAX + 1);
      const obj = {
       
       
        // y轴的值
        'value': nowValue,
        'pointStyle': {
       
       
          // 点的形状
          'shape': 'circle',
          'size': CommonConstants.LINE_POINT_SIZE,
          'fillColor': '#FFFFFF',
          'strokeColor': '#0A59F7'
        }
      };
      dataArray.push(obj);
    }
    this.lineData = [
      {
       
       
        // 曲线颜色
        strokeColor: '#0A59F7',
        // 渐变填充颜色
        fillColor: '#0A59F7', 
        data: dataArray,
        gradient: true
      }
    ];
  }
}

Implement the changeBar method to update the histogram data. Traverse all the data groups of the bar chart. After obtaining the data of each group, traverse each group of data again, generate random numbers and reassign barData.

// index.js
export default {
       
       
  ...
  // 更新柱状图数据
  changeBar() {
       
       
    for (let i = 0; i < this.barGroup; i++) {
       
       
      const dataArray = this.barData[i].data;
      for (let j = 0; j < this.dataLength; j++) {
       
       
        dataArray[j] = Math.floor(Math.random() * CommonConstants.BAR_RANDOM_MAX + 1);
      }
    }
    this.barData = this.barData.splice(0, this.barGroup + 1);
  }
}

6. Summary

You have completed this Codelab study and learned the following knowledge points:

  1. The use of components such as switch and chart.

Guess you like

Origin blog.csdn.net/HarmonyOSDev/article/details/132709205
Recommended