使用 Flutter 绘制平滑的线条

lsc*_*lsc 3 dart flutter

我正在尝试使用自定义画家用颤动来绘制线条。即https://medium.com/flutter-community/drawing-in-flutter-using-custompainter-307a9f1c21f8

如何让用户绘制的线条变得流畅?

Mol*_*0ko 9

要绘制平滑的线条路径,可以使用.cubicTo()Path 方法。它应用三次贝塞尔插值。这是平滑线条画家的代码示例:

class SmoothLinePainter extends CustomPainter {
  final Color lineColor;
  final List<double> values;

  SmoothLinePainter(this.lineColor, this.values);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = lineColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    final path = Path();

    final yMin = values.reduce(min);
    final yMax = values.reduce(max);
    final yHeight = yMax - yMin;
    final xAxisStep = size.width / values.length;
    var xValue = 0.0;
    for (var i = 0; i < values.length; i++) {
      final value = values[i];
      final yValue = yHeight == 0
          ? (0.5 * size.height)
          : ((yMax - value) / yHeight) * size.height;
      if (xValue == 0) {
        path.moveTo(xValue, yValue);
      } else {
        final previousValue = values[i - 1];
        final xPrevious = xValue - xAxisStep;
        final yPrevious = yHeight == 0
            ? (0.5 * size.height)
            : ((yMax - previousValue) / yHeight) * size.height;
        final controlPointX = xPrevious + (xValue - xPrevious) / 2;
        // HERE is the main line of code making your line smooth
        path.cubicTo(
            controlPointX, yPrevious, controlPointX, yValue, xValue, yValue);
      }
      xValue += xAxisStep;
    }
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(_LineChartPainter old) =>
      old.lineColor != lineColor && old.values != values;
}
Run Code Online (Sandbox Code Playgroud)

这是两张图片,显示了使用.lineTo().cubicTo()方法之间的区别:

  1. 路径.lineTo(...)

.lineTo()

  1. 路径.cubicTo(...)

在此输入图像描述