我正在尝试使用自定义画家用 flutter 画线。即https://medium.com/flutter-community/drawing-in-flutter-using-custompainter-307a9f1c21f8
如何使用户绘制的线条流畅?
最佳答案
要绘制平滑线路径,您可以使用 Path 的 .cubicTo()
方法。它应用三次贝塞尔插值。这是平滑线画家的代码示例:
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;
}
这里有两张图片显示了使用 .lineTo()
和 .cubicTo()
方法之间的区别:
- path.lineTo(...)
- path.cubicTo(...)
关于flutter - 使用 Flutter 绘制流畅的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58673381/