Directory:

1, the preface

2, the background,

3. Component effect display

4. Sample analysis

5. Library parsing

6, “Hongmeng Open source third-party components” series of articles collection

preface

This component is based on the Android platform chart component MPAndroidChart (github.com/PhilJay/MPA…

background

MPAndroidChart for Android has over 33,000 stars and 8.3k forks on GitHub, making it the most widely used and experienced open source chart library. It has the ability to draw line chart, pie chart, radar chart and other charts, users only need to write a data interface, you can achieve all kinds of beautiful data curve drawing, to a certain extent to meet the needs of most business.

This component is a modified version of MPAndroidChart named MPAndroidChart_ohos, which implements its core functions.

Component Effect display

Currently MPAndroidChart_ohos has two kinds of chart drawing ability: line chart and histogram. Below will show its line graph and histogram drawing effect respectively.

1. Line chart

Figure 1 shows a line chart generated from random data. MPAndroidChart_ohos inherits the excellent features of the original MPAndroidChart and provides a variety of user customization interfaces, such as:

(1) X and Y axes are customized. Users can customize the positions of X and Y axes. For example, in this sample, the left Y axis and the upper X axis are drawn.

(2) Auxiliary line customization. The user can choose whether to display the auxiliary line (or grid line), and can also set the position of the auxiliary line freely.

(3) Chart beautification. The user can set various properties of the graph curve (color, thickness, etc.) and also fill in the area covered by the curve.

FIG. 1 Line drawing effect

2. Histogram

Figure 2 is a graph based on the hypothetical scenario “Concession store revenue from January 1 to 15, 2020”. With this background, a histogram is made using MPAndroidChart_ohos.

FIG. 2 Histogram rendering effect

The Sample analysis

Figure 3 Sample engineering structure

Figure 1 and Figure 2 are drawn mainly by calling the capabilities in the Library, and the implementation in Sample is mainly done by the two files shown in the red box in Figure 3.

If the user wants to draw a diagram, just complete the following steps:

(1) Select the type of chart.

(2) Set the properties.

(3) Import data.

1. Select the chart type

MPAndroidChart_ohos provides the ability to draw line charts and histograms. Users only need to select the ability to use according to their own needs.

LineChart chart = new LineChart(context); Chart = new BarChart(context); // Initialize the histogram 1.2.Copy the code

2. Set properties

MPAndroidChart_ohos provides the ability to customize chart styles by calling the Library exposed interface to add, modify, and delete attributes to a chart. For example, if the user wants to customize the axis, he can instantiate the object of the XAxis class, and then modify the color of the X axis through various methods of the object, and set the maximum value, minimum value, etc. :

XAxis xAxis = chart.getXAxis(); // instantiate xaxis.setaxismaximum (20f); // Set the xaxis.setaxisminimum (0f); xAxis.setAxisLineColor(Color.BLACK.getValue()); 2.Copy the code

LimitLine (x = 2, x = 2, x = 2, x = 2, x = 2, x = 2);

LimitLine llXAxis = new LimitLine(2f, "x=2"); // instantiate llxaxis.setlineWidth (4f); // Property set llxaxis.setlabelPosition (limitlabelPosition.right_bottom); llXAxis.setTextSize(10f); llXAxis.setTypeface(Font.DEFAULT); 1.2.3.4.5.Copy the code

3. Import data

In MPAndroidChart_ohos, different types of charts have different data classes, such as line chart data class LineData, histogram data class BarData, why not just a simple int[] or float[] data class? This is because data classes in MPAndroidChart_ohos not only carry data, but also need to carry chart-related properties such as curve color, curve thickness, data point color, size, etc. The purpose of this will be discussed in the subsequent Library analysis.

Taking the broken line graph as an example, the data import process is as follows:

(1) Create LineDataSet class:

LineDataSet set1 = new LineDataSet(values, label); 1.Copy the code

Values are the type of data that the consumer wants to draw, typically float[], and label is the label for such data.

(2) Place one or more classes of data into an ArrayList

ArrayList<ILineDataSet> dataSets = new ArrayList<>(); dataSets.add(set1); 1.Copy the code

(3) Make ArrayList into LineData data class and pass it to Chart

LineData data = new LineData(dataSets); chart.setData(data); 1.2.Copy the code

The Library parsing

1. Comparison of engineering structures

FIG. 4 Engineering structure comparison of MPAndroidChart_ohos(top) and MPAndroidChart (bottom)

From the comparison of the two figures in Figure 4, it can be seen that MPAndroidChart_ohos is developed according to the structure of MPAndroidChart project and has realized its main functions. Compared to MPAndroidChart, MPAndroidChart_ohos lacks the exception, highlight and Jobs folders, but it does not affect the use of its main functions.

2, multi-device adaptation

In order to increase the adaptability of multiple devices, MPAndroidChart internally calculates the relative positions of various components in the graph in the unit of DP (Density Independent Pixels), and uniformly converts DP data into Pixel data when drawing the graph. In this process, the system needs to provide some display information. In Android, this information is provided by DisplayMetrics, which can be retrieved from the context:

Resources res = context.getResources(); mMetrics = res.getDisplayMetrics(); 1.2.Copy the code

Then, DisplayMetrics can obtain the DPI of the screen, dp * DPI is the pixel of the screen:

public static float convertDpToPixel(float dp) { return dp * mMetrics.density; } 1.2.3.Copy the code

In hongmeng system, display information is obtained through the DisplayAttribute class. The following code can obtain the DisplayAttribute:

Display display = DisplayManager.getInstance().getDefaultDisplay(this.getContext()).get(); 
DisplayAttribute displayAttribute = display. getAttributes() 1.2.
Copy the code

You can see that it’s a little bit different from Android. After obtaining DisplayAttribute, screen DPI can be obtained. It should be noted that the interface representing DPI is different from Android:

    public static float convertDpToPixel(float dp) { 
        return dp * mMetrics.densityPixels; 
    } 1.2.3.
Copy the code

3. Axis drawing

Axis is the benchmark for a chart, and in MPAndroidChart, axis even serves as the benchmark for chart categories! It seems that MPAndroidChart provides more than ten kinds of chart drawing capabilities. In fact, these more than ten kinds of charts are made based on two axes, namely the plane rectangular coordinate system and the polar coordinate system.

In the cartesian coordinate system, MPAndroidChart implements broken line, scatter, histogram, bubble, candle, etc.

In polar coordinate system, MPAndroidChart realizes pie chart and radar chart.

In MPAndroidChart_ohos, axis related classes are distributed in the Components folder and renderer folder:

Figure 5 Axis class and axis drawing class

The AxisBase class mainly defines the attributes that the axis should have, such as color, thickness, position, scale, label, maximum value, and so on. XAxis and YAxis inherit from AxisBase, and define the attributes of the X and Y axes respectively. For example, the position attribute of the X axis should be “Top”, “BOTTOM”, “TOP_INSIDE”, “BOTTOM_INSIDE”, or “BOTH_SIDED”. The Y axis, unlike the X axis, should have the position attribute of “LEFT” or “RIGHT”.

The AxisRenderer class is the base class for drawing axes. It defines the properties and methods necessary for drawing axes, such as Paint for drawing axes, labels, auxiliary lines, and grid points, and corresponding method interfaces. The XAxisRenderer and the YAxisRenderer inherit from the AxisRenderer and implement the interface for drawing, which really does the axis drawing. Other such as XAxisRenderHorizontalBarChart class look from the name is also easy to learn that in some special chart drawing axis.

4. Data rendering

FIG. 6 Data classes related to line charts

As mentioned in the Sample analysis, different data classes are required to host data and attributes for different types of charts. The inheritance relationship of data classes is a complicated part of MPAndroidChart. For example, the LineData class we need to draw line charts is inherited from:

public class LineData extends BarLineScatterCandleBubbleData<ILineDataSet> {1.
Copy the code

The class name is a bit long, but that’s ok, keep looking:

public abstract class BarLineScatterCandleBubbleData<T extends IBarLineScatterCandleBubbleDataSet<? extends Entry>> extends ChartData<T> {1.
Copy the code

The ChartData class should be the root:

public abstract class ChartData<T extends IDataSet<? extends Entry>> {  1.
Copy the code

This may not seem like much, but it is worth noting that there are a lot of interfaces and generic parameters that need to be implemented, and these interfaces and generics can be nested down several layers, which makes migration difficult. Let’s take a look at what these data classes do.

ChartData class is the base class data classes, in which the first define the data of the upper and lower bounds are floating point Numbers to represent the maximum and minimum values, at the same time, this class provides some data processing methods, such as the upper and lower, of if you find any more than the number will be the compulsory assignment for upper and lower bound, avoid data overflow errors. At the same time, this class also provides data query methods such as the number of data points, query data X, Y value, query label, query maximum, minimum and other data query methods.

BarLineScatterCandleBubbleData and LineData were primary and secondary packaging of ChartData itself does not add any methods, only by implementing an interface with a variety of generic parameter to limit the data format into it.

Figure 7 line graph drawing class

So how are data points and curves plotted on a graph? DataRenderer is the base class for drawing data, which writes out abstract methods for drawing data, curves, labels, and so on. Continuing with the broken line diagram, These abstract methods will be DataRendereraBarLineScatterCandleBubbleRendereraLineScatterCandleRadarRendereraLineRadarRendereraLineChartRender Er was gradually implemented in the inheritance path, and eventually LineChartRenderer realized the full ability to draw line charts.

Project contributor

Wu Shengyao, Zheng Senwen, Zhu Wei, Chen Mei, You, Zhang Xinxin

Author: Zhu Wei ISRC

For more information, visit Harmonyos.51cto.com, a collaboration between 51CTO and Huawei