如何使用CustomPainter绘制曲线图?

4
我正在尝试绘制一条带有光滑曲线的折线图,类似于fl_chart中的这个示例:

enter image description here

我尝试使用quadraticBezierTo,但它没有起作用:

enter image description here

这是我的代码,还有其他方法吗?
import 'package:flutter/material.dart';

class DrawLines extends StatefulWidget {
  final Coordinates lineCoordinates;
  final double yHeight;

  DrawLines({required this.lineCoordinates, required this.yHeight});

  @override
  _DrawLinesState createState() => _DrawLinesState();
}

class _DrawLinesState extends State<DrawLines> {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      foregroundPainter: LinePainter(
          coordinates: widget.lineCoordinates, yHeight: widget.yHeight),
    );
  }
}

class CoordValues {
  late double x;
  late double y;

  CoordValues({required this.x, required this.y});
}

class Coordinates {
  late CoordValues startCoords;
  late CoordValues endCoords;

  Coordinates({required this.startCoords, required this.endCoords});
}

class LinePainter extends CustomPainter {
  late Coordinates coordinates;
  late double yHeight;

  LinePainter({required this.coordinates, required this.yHeight});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Color(0xFF295AE3)
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 2;

    //curved
    Path path = Path();

    path.moveTo(coordinates.startCoords.x, yHeight - coordinates.startCoords.y);
    path.quadraticBezierTo(
        coordinates.startCoords.x + 15,
        coordinates.startCoords.y,
        coordinates.endCoords.x + 15,
        yHeight - coordinates.endCoords.y);
    //for every two points one line is drawn

  

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

我认为我的问题很简单,但不知何故stackoverflow要求我多写一些。
2个回答

2
Path drawPath(bool closePath) {
  final width = MediaQuery.of(context).size.width;
  final height = chartHeight;
  final path = Path();
  final segmentWidth = width / 3 / 2;
  path.moveTo(0, height);
  path.cubicTo(segmentWidth, height, 2 * segmentWidth, 0, 3 * segmentWidth, 0);
  path.cubicTo(4 * segmentWidth, 0, 5 * segmentWidth, height, 6 * segmentWidth, height);

  return path;
}

这个教程非常适合学习IT技术,所有内容都有很好的解释。请查看下面的链接:

https://www.kodeco.com/32557465-curved-line-charts-in-flutter


-1

你可以在这里使用 fl_chart 依赖项,这是链接


https://pub.dev/packages/fl_chart - Mirza Azmathullah
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接