在Custom Painter Flutter的路径中将端点与起点连接时如何避免锐利的边缘/角度?

时间:2019-07-02 12:56:27

标签: flutter bezier

Attached image is current output, Issue: Left top, sharp edge/angle can be seen.出现问题,即在使用“自定义画笔”绘制形状时,在将最后一点与第一个点连接时,消除了尖锐的边缘/角度。

我正在尝试使用CustomPainter创建自定义形状。我使用一些要点创建了路径。对于绘制路径,我使用的是Bezier。我的代码如下。但是,当最后一点连接到第一个点时,它将创建锐角。我该如何避免呢?

// preparing path points for shape.
for (int i = 0; i < steps; i++) {
  borderPoints.add(BorderPoint(xPoint, yPoint, radian, randomRadius, MovementDirection.INWARD));
}
borderPoints.add(borderPoints[0]);

// here, we are creating path for our shape.
jellyPath.moveTo(borderPoints[0].dx, borderPoints[0].dy);
int i = 1;

for (i = 1; i < borderPoints.length - 2; i++) {
  var xc = (borderPoints[i].dx + borderPoints[i + 1].dx) / 2;
  var yc = (borderPoints[i].dy + borderPoints[i + 1].dy) / 2;
  jellyPath.quadraticBezierTo(
      borderPoints[i].dx, borderPoints[i].dy, xc, yc);
}
jellyPath.quadraticBezierTo(borderPoints[i].dx, borderPoints[i].dy, borderPoints[i + 1].dx, borderPoints[i + 1].dy);

在“路径”中连接端部时预期平滑曲线。

1 个答案:

答案 0 :(得分:3)

尝试使用此简单的绘图代码(无论如何,您都必须对其进行修改以使其与BorderPoint一起使用)

var p = Paint()
  ..style = PaintingStyle.stroke
  ..color = Colors.deepPurple
  ..strokeWidth = 2;

var points = [
  Offset(100, 100),
  Offset(200, 150),
  Offset(250, 300),
  Offset(150, 350),
  Offset(150, 250),
  Offset(50, 200),
];

// you can remove "controlPaint" - it is for testing only
var controlPaint = Paint()..color = Color(0x880000ff);
var path = Path();
var mid = (points[0] + points[1]) / 2;
path.moveTo(mid.dx, mid.dy);
for (var i = 0; i < points.length; i++) {
  var p1 = points[(i + 1) % points.length];
  var p2 = points[(i + 2) % points.length];
  mid = (p1 + p2) / 2;
  path.quadraticBezierTo(p1.dx, p1.dy, mid.dx, mid.dy);

  // draw control points and lines: switch it on by pressing 'p' key
  // when executing "flutter run" command
  // note it is for testing purposes only
  if (debugPaintSizeEnabled)
    canvas
      ..drawCircle(mid, 3, controlPaint)
      ..drawCircle(points[i], 5, controlPaint)
      ..drawLine(points[i], p1, controlPaint);
}
canvas.drawPath(path, p);