Preface
Because a project needs to show the changes in temperature, humidity, carbon dioxide concentration, and illumination intensity of a system over a period of time, you need to use the line chart control to search online, open source control libraries such as AChartEngine and HoloGraphLibrary are found.
Although AChartEngine has many functions, it is not easy to use and the interface is not beautiful. Although HoloGraphLibrary is very beautiful, it has few functions.
You decide to develop the line chart control and exercise on your own.
The following functions are required:
Scale adaptive (adjust the scale value and interval based on the data );
More data needs to be displayed by sliding.
Note the following:
Save resources and check the start and end points of rendering;
Handle critical values.
Start
The final code is as follows, with detailed comments, which readers can understand:
Package hk. jerry. linechart;
Import java. util. ArrayList;
Import java. util. List;
Import android. annotation. SuppressLint;
Import android. content. Context;
Import android. graphics. Canvas;
Import android. graphics. Color;
Import android. graphics. Paint;
Import android. graphics. Paint. Align;
Import android. util. AttributeSet;
Import android. view. MotionEvent;
Import android. view. View;
@ SuppressLint ({"InlinedApi", "ClickableViewAccessibility "})
Public class LineChartView extends View {
Private Paint paintAxis = new Paint (); // axis and scale painter
Private Paint paintLine = new Paint (); // Line and title painter
Private Paint paintPoint = new Paint (); // data point painter
Private Paint paintClear = new Paint (); // clear the Paint brush
Private String title = ""; // title
Private int chartStartX; // Chart X axis start coordinate
Private int chartStopX; // The ending coordinate of the x axis of the chart.
Private int chartStartY; // The starting coordinate of the y axis of the chart.
Private int chartStopY; // end coordinate of the y axis of the chart
Private int chartHeight; // chart height
Private int chartWidth; // chart width
Private float max; // The maximum value of a data point.
Private float min; // minimum value of a data point
Private List dataSets = new ArrayList (); // dataset
Private int levelsX; // number of scales on the x axis
Private int levelsY; // Number of Y-axis scales
Private float spaceX; // x axis scale spacing
Private float spaceY; // y-axis scale spacing
Private int unit = 5; // The difference between scales
Private int length; // The x-axis length of the valid area of the chart.
Private int downX; // the x axis coordinate pressed before the user slides
Private int offsetLeft = 50; // Offset
Private boolean scrollabled = true; // whether sliding is allowed
Private boolean drew = false; // whether the image has been painted
Private int maxDataSetsLength =-1; // maximum dataset length.-1 is unlimited.
Public LineChartView (Context context ){
Super (context );
}
Public LineChartView (Context context, AttributeSet attrs ){
Super (context, attrs );
}
@ Override
Protected void onDraw (Canvas canvas ){
Super. onDraw (canvas );
If (dataSets. isEmpty () {// if the dataset is empty, no painting is performed.
If (drew ){
Canvas. drawRect (0, 0, getWidth (), getHeight (), paintClear );
} Else {
Return;
}
}
Drew = true; // otherwise, draw and Mark drew as true.
Init ();
Canvas. drawColor (Color. WHITE); // background Color
// Draw the x axis scale, data point, and line
Canvas. drawLine (chartStartX, chartStopY, chartStopX, chartStopY, paintAxis );
PaintAxis. setTextAlign (Align. CENTER );
Int j = (int) Math. ceil (0-offsetLeft/spaceX)-1; // This action is used as a buffer to draw multiple data points before and after the display area.
For (int I = 0; I <= levelsx = ""> 10? 10: levelsX) + 1; I ++, j ++ ){
If (j <0 | j> = dataSets. size () {// prevent array subscript from exceeding the bounds
Continue;
}
DataSet currentPoint = dataSets. get (j );
Float x = getPointX (j );
Canvas. drawLine (x, chartStopY, x, chartStopY + 5, paintAxis); // draw the scale
Canvas. drawText (currentPoint. name, x, chartStopY + 5 + 20, paintAxis); // draw the scale text
// Draw a line
Float y = getPointY (currentPoint. value );
If (j + 1 <dataSets. size ()){
Canvas. drawLine (x, y, getPointX (j + 1), getPointY (dataSets. get (j + 1). value), paintLine );
}
// Draw data points
Canvas. drawCircle (x, y, 5, paintPoint );
}
// Overwrite the out-of-bounds content before the y axis is drawn
Canvas. drawRect (0, 0, chartStartX, getHeight (), paintClear );
// Draw the y axis scale
Canvas. drawLine (chartStartX, chartStartY, chartStartX, chartStopY, paintAxis );
PaintAxis. setTextAlign (Align. RIGHT );
For (int I = 0; I <levelsY; I ++ ){
Float pointY = chartStopY-(I + 1) * spaceY; // position of point Y
Canvas. drawLine (45, pointY, chartStartX, pointY, paintAxis); // draw the scale
Canvas. drawText (String. valueOf (int) min + (I) * unit), 40, pointY + 8, paintAxis); // draw the scale text
}
// Draw the title
If (title! = Null &&! Title. equals ("")){
Canvas. drawText (title, getWidth ()/2, 30, paintLine );
}
}
/*
* Obtain the X coordinate value based on the data point number
*/
Private float getPointX (int I ){
Return chartStartX + (I) * spaceX + offsetLeft;
}
/*
* Obtain the Y coordinate value based on the data value
*/
Private float getPointY (float value ){
Int exceedNum = (int) (Math. ceil (value-min)/unit) + 1; // calculate the number of points of the scale to be exceeded (excluding the zero line)
Float y = chartStopY-exceedNum * spaceY-(value-min) % unit/unit * spaceY;
Return y;
}
Public void setScrollable (boolean scrollabled ){
This. scrollabled = scrollabled;
}
/*
* Set the title
*/
Public void setTitle (String title ){
This. title = title;
Invalidate ();
}
/*
* Clear charts
*/
Public void empty (){
DataSets = new ArrayList ();
Title = "";
Length = 0;
Invalidate ();
}
/*
* Initialize painter and computation data
*/
Private void init (){
// Calculate the chart
ChartStartX = 50;
ChartStopX = getWidth ();
ChartStartY = 50;
ChartStopY = getHeight ()-30;
ChartWidth = chartStopX-chartStartX;
ChartHeight = chartStopY-chartStartY;
// Axis painter
PaintAxis. setAntiAlias (true );
PaintAxis. setStrokeWidth (3 );
PaintAxis. setColor (Color. parseColor ("#858585 "));
PaintAxis. setTextSize (18 );
// Data point painter
PaintPoint. setAntiAlias (true );
PaintPoint. setStrokeWidth (3 );
PaintPoint. setStyle (Paint. Style. FILL_AND_STROKE );
PaintPoint. setColor (Color. parseColor ("# 00aa3a "));
// Line Painter
PaintLine. setAntiAlias (true );
PaintLine. setStrokeWidth (5 );
PaintLine. setTextAlign (Align. CENTER );
PaintLine. setTextSize (35 );
PaintLine. setColor (Color. parseColor ("# 00aa3a "));
// Erase the paint brush
PaintClear. setColor (Color. WHITE );
// Obtain the maximum and minimum values for easy calculation
Min = max = dataSets. get (0). value;
For (int I = 1; I <dataSets. size (); I ++ ){
DataSet set = dataSets. get (I );
If (set. value <min) {min = set. value;} if (set. value> max ){
Max = set. value;
}
}
// Calculate data related to the X and y axes for later drawing
Float minus = max-min;
Unit = (int) Math. ceil (minus/10 );
Unit = 0? 1: unit; // if the spacing is 0, change it to 1 to prevent the scale from increasing
LevelsY = (int) (Math. ceil (max-min)/unit); // number of scales to be drawn on the y axis
If (levelsY = 0) {// if there are only 0 scales, that is, a scale is always added when the trend is flat, so that the only scale can be drawn to the center
LevelsY ++;
}
SpaceY = chartHeight/(levelsY + 1); // The distance between the Y axis scales, + 1 is to leave space for the front and back
LevelsX = dataSets. size (); // number of scales to be drawn on the x axis
SpaceX = chartWidth/(levelsX> 10? 10: levelsX + 1); // The distance between the x axis scales. + 1 is used to leave space for the front and back of the scale.
Length = (int) (dataSets. size () * spaceX );
}
/*
* Add a dataset
*/
Public void addDataSet (DataSet dataSet ){
If (maxDataSetsLength! =-1 & dataSets. size ()> maxDataSetsLength ){
DataSets. remove (0 );
}
DataSets. add (dataSet );
ScrollToEnd ();
}
Public void setMaxDataSetsLength (int maxDataSetsLength ){
This. maxDataSetsLength = maxDataSetsLength;
}
/*
* Scroll to the header
*/
Public void scrollToStart (){
If (! Drew ){
Invalidate ();
}
OffsetLeft = 50;
Invalidate ();
}
/*
* Scroll to the end
*/
Public void scrollToEnd (){
If (! Drew ){
Invalidate ();
}
OffsetLeft = chartWidth> = length? 50: (0-(length-chartWidth)-50 );
Invalidate ();
}
/*
* Whether the image has been rolled to the end
*/
Public boolean isScrolledToStart (){
Return offsetLeft> = 50;
}
/*
* Whether to scroll to the header
*/
Public boolean isScrolledToEnd (){
Return chartWidth> = length? (OffsetLeft <= 50): (offsetLeft <0-(length-chartWidth ));
}
/*
* Set a dataset
*/
Public void setDataSets (List dataSets ){
Length = 0;
This. dataSets = dataSets;
Invalidate ();
ScrollToEnd ();
}
/*
* Touch time to detect whether the user slides
*/
@ SuppressLint ("ClickableViewAccessibility ")
@ Override
Public boolean onTouchEvent (MotionEvent event ){
Switch (event. getAction ()){
Case MotionEvent. ACTION_DOWN:
DownX = (int) event. getRawX ();
Break;
Case MotionEvent. ACTION_MOVE:
If (! Scrollabled)
Return true;
// DistanceX <0 indicates that the finger slides to the left, and distancex> 0 indicates that the finger slides to the right.
Int distanceX = (int) event. getRawX ()-downX; // The moving distance.
OffsetLeft + = distanceX;
DownX = (int) event. getRawX ();
If (isScrolledToStart ()){
ScrollToStart ();
} Else if (isScrolledToEnd ()){
ScrollToEnd ();
} Else {
Invalidate ();
}
Break;
Case MotionEvent. ACTION_UP:
Break;
}
Return true;
}
Public static class DataSet {
Public String name;
Public float value;
Public DataSet (String name, float value ){
This. name = name;
This. value = value;
}
}
}
We can use the following in the layout:
<Hk. jerry. linechart. LineChartView
Android: id = "@ + id/lc_test"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"/>
Then add the data:
LineChartView lcHistory = (LineChartView) findViewById (R. id. lc_test );
// Test data lcHistory. setTitle ("test chart ");
Random random = new Random (10 );
For (I = 0; I <50; I ++ ){
LcHistory. addDataSet (new DataSet (50-I) + "minutes ago", random. nextInt (40 )));
}
Running effect