flutter drawPath无法绘制问题,路径不显示?

1,453 阅读1分钟
 void paint(Canvas canvas, Size size) {
    Paint paint = new Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill
      ..color = Colors.black
      ..strokeWidth = 10;
    Path path = new Path();
    path.moveTo(0, 0);
    path.lineTo(100, 100);
    path.lineTo(200, 200);
    canvas.drawPath(path, paint);
    canvas.drawCircle(Offset(100, 100), 20, paint);
  }

发现drawCircle可以被绘制,drawPath却无法绘制的问题:

官方解释说:

Draws the given [Path] with the given [Paint]. 
Whether this shape is filled or stroked (or both) is controlled by [Paint.style].
If the path is filled, then sub-paths within it are implicitly closed (see [Path.close]).

意思是,当PaintingStyle是fill时,path会被自动调用path.close()方法,这个方法的作用是闭合路径,把PaintingStyle改成stroke就可以显示了。

那么为什么会出现这种问题呢?

在上面的代码中,path的三个点是一条直线,而PaintingStyle是fill,这意味着path无法被闭合,因此无法被渲染,但却没有抛出异常,这是个小坑。

研究了好久才发现这问题...我居然第一次使用drawPath恰好撞上path是一条直线 [捂脸] 。