Plot numbers as Line graph on canvas

The following code plots an array of integers as a line graph on canvas of a View class.

public class SkView extends View{

private Paint myPaint;
int viewWidth = 0;
int viewHeight = 0;

int[] humidity = new int[]{ 40, 36, 79, 90, 54, 62, 80};

public SkView(Context context){
super(context);
myPaint = new Paint();
}

@Override
protected void onDraw(Canvas canvas) {
viewWidth = this.getMeasuredWidth();
viewHeight = this.getMeasuredHeight();

myPaint.setStyle(android.graphics.Paint.Style.STROKE);
myPaint.setStrokeWidth(4);
myPaint.setColor(Color.BLACK);

canvas.drawLine(viewWidth/10, viewHeight*9/10, viewWidth*9/10, viewHeight*9/10, myPaint);

canvas.drawLine(viewWidth/10, viewHeight*9/10, viewWidth/10, viewHeight/10, myPaint);

int marginWidth = viewWidth/10;
int marginHeight = viewHeight/10;
int graphLeft = marginWidth;
int graphBottom = viewHeight - marginHeight;
int graphWidth = viewWidth*8/10;
int graphHeight = viewHeight*8/10;

int gap = graphWidth/humidity.length;

int max = humidity[0];

for (int i =0; i<humidity.length; i++){
if(max < humidity[i]) {
max = humidity[i];
}
}

int factor = graphHeight/max;

for (int n = 0; n<humidity.length-1; n++){
canvas.drawLine(marginWidth + n*gap, graphBottom-(humidity[n]*factor), marginWidth + (n+1)*gap, graphBottom-(humidity[n+1]*factor), myPaint);
}

}

}

This View class can be used in any Activity by calling setContentView(new SkView(this)); or it can be added to a ViewGroup like LinearLayout e.g. linear1.addView(new SkView(this));

Leave a Reply