Reputation: 2558
At the moment, I have found 2 ways that could be used to draw line, which possibly could be improved into a line chart:
using canvas.drawCircle(..)
and canvas.drawLine(..)
canvas.drawCircle(new Offset(2.0, 5.0), 10.0, paint);
canvas.drawCircle(new Offset(50.0, 100.0), 10.0, paint);
canvas.drawLine(new Offset(2.0, 5.0), new Offset(50.0, 100.0), paint);
using canvas.drawPoints(PointMode.lines, ..)
I prefer #2, because I can pass all points into one function canvas.drawPoints(..)
.
List offsetList = [new Offset(2.0, 5.0), new Offset(50.0, 100.0),];
canvas.drawPoints(PointMode.lines, offsetList, paint);
Paint object:
final paint = new Paint()
..color = Colors.blue[400]
..strokeCap = StrokeCap.round
..style = PaintingStyle.fill;
Question:
At the moment, I think #2 is a better way to draw line chart, but how can I make the points visible like #1? Do you know any other better ways that could be use to draw line chart?
Upvotes: 5
Views: 5324
Reputation: 101
I am sure by now you are not worrying about this anymore so for anyone that would like another way. You can also use canvas.drawPath(...)
, here is a simple implementation for a line graph using it.
@override
void paint(Canvas canvas, Size size) {
canvas.translate(0.0, size.height);
final Path path = new Path();
final Paint paint = new Paint();
paint.color = Colors.blue[100];
final double center = size.height/2;
path.moveTo(0.0, 0.0); // first point in bottom left corner of container
List<double> ypos = [10.0, 40.0, 100.0, 60.0, 40.0, 55.0, 200.0]; // random y points
path.lineTo(0.0, - (ypos[0] + center)); // creates a point translated in y inline with leading edge
final int dividerCnst = ypos.length; // number of points in graph
for(int i = 1; i < dividerCnst + 1; i++){
path.lineTo(size.width/dividerCnst * i - size.width/(dividerCnst * 2), - (ypos[i-1] + center));
}
path.lineTo(size.width, -(ypos[dividerCnst - 1] + center)); // the last point in line with trailing edge
path.lineTo(size.width, 0.0); // last point in bottom right corner of container
path.close();
canvas.drawPath(path, paint);
canvas.restore();
}
(0,0) is top left so to change this I do canvas.translate(0.0, size.height)
to translate the origin to the bottom left corner. In Fluttr +ve is downwards to the Y values are negative and I have added it to the variable center so my point don't lie at the bottom but higher up. This result returns this.
Hope this helps someone. Peace.
Upvotes: 8