如何为Flutter应用程序绘制折线图?

时间:2017-10-17 21:10:56

标签: dart flutter

目前,我找到了两种可用于绘制线条的方法,可以将其改进为折线图:

  1. 使用canvas.drawCircle(..)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);
    

    point_line

  2. 使用canvas.drawPoints(PointMode.lines, ..)我更喜欢#2,因为我可以将所有点传递给一个函数canvas.drawPoints(..)

     List offsetList = [new Offset(2.0, 5.0), new Offset(50.0, 100.0),];
     canvas.drawPoints(PointMode.lines, offsetList, paint);
    

    line

  3. 绘制对象:

        final paint = new Paint()
      ..color = Colors.blue[400]
      ..strokeCap = StrokeCap.round
       ..style = PaintingStyle.fill;
    

    问题:

    目前,我认为#2是绘制折线图的更好方法,但我怎样才能让这些点像#1一样可见?你知道还有其他更好的方法来绘制折线图吗?

1 个答案:

答案 0 :(得分:3)

我相信你现在不再担心这个了,所以对于那些想要另一种方式的人来说。您也可以使用canvas.drawPath(...),这是使用它的折线图的简单实现。

@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)位于左上角,所以为了改变这一点,我做canvas.translate(0.0, size.height)将原点转换为左下角。在Fluttr + ve向下到Y值是负的,我已将它添加到变量中心,所以我的观点不是在底部而是在更高的位置。这个结果会返回这个。

enter image description here

希望这有助于某人。和平。