Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Fill color below the line chart

I am building a line chart for one of our applications. The line part in the chart is working fine but now I have to fill the area below the line with a color, something like this image below.

enter image description here

I am using this code to draw the line on to a bitmap using a canvas.

    List<Float> xCoordinates = (List<Float>) coordinates[0];
    List<Float> yCoordinates = (List<Float>) coordinates[1];

    for (int i = 0; i < xCoordinates.size(); i++) {
        if (!firstSet) {
            x = xCoordinates.get(i);
            y = yCoordinates.get(i);
            p.moveTo(x, y);
            firstSet = true;
        } else {
            x = xCoordinates.get(i);
            y = yCoordinates.get(i);
            p.lineTo(x, y);
        }
    }

    textureCanvas.drawPath(p, pG);

What I need to know is, is there a way to easily find the area below the line and make it a color or will I have to calculate each area between 3 points for the graph and fill it with a color?

I cannot use existing chart libraries like AchartEngine, ChartDroid, aFreeChart ect.

like image 706
the-ginger-geek Avatar asked Apr 22 '13 06:04

the-ginger-geek


1 Answers

Found a solution

I first painted the gradient, after that I painted the line chart and erased all along the line by creating another path that followed the line chart and closed it up at the end. After that I painted the area transparent to erase the top part of the gradient.

    List<Float> xCoordinates = coordinates.first;
    List<Float> yCoordinates = coordinates.second;
    for (int i = 0; i < xCoordinates.size(); i++) {
        if (!firstSet) {
            x = xCoordinates.get(i);
            y = yCoordinates.get(i);
            linePath.moveTo(x, y);

            erasePath.moveTo(x, 0);
            erasePath.lineTo(x, y);

            firstSet = true;
        } else {
            x = xCoordinates.get(i);
            y = yCoordinates.get(i);
            linePath.lineTo(x, y);
            erasePath.lineTo(x, y);
        }
    }

    erasePath.lineTo(getWidth(), y);
    erasePath.lineTo(getWidth(), 0);
    erasePath.lineTo(0, 0);

    getTextureCanvas().drawPath(erasePath, clear);
    getTextureCanvas().drawPath(linePath, pG);

The result looked like this

enter image description here

Another way to do this is to follow the path exactly and clip around the bottom edges and just paint the gradient inside the second path. This will give the same result but all content above the graph will be kept and nothing will be erased.

like image 91
the-ginger-geek Avatar answered Oct 23 '22 22:10

the-ginger-geek