如何在Flutter CustomPaint中绘制轴外的线

dhxwm5r4  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(225)

我有一个Container,父节点是CustomPaint。在CustomPaint中,我只是在Container的一半周围画一条线。该线的一半宽度在Container内,另一半宽度在Container外。我想把线完全画在Container之外。我如何才能实现这种行为?先谢谢你了。
下面是它现在的样子:

下面是我的代码:

Center(
        child: CustomPaint(
          painter: SeatDecorator(),
          child: Container(
            width: 150,
            height: 150,
            color: Colors.blue.withOpacity(0.5),
          ),
        ),
      )

我的CustomPainter:

class SeatDecorator extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.square
      ..style = PaintingStyle.stroke
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = 8;

    Path path = Path();
    path.moveTo(0, size.height / 2);
    path.lineTo(0, 0);
    path.lineTo(size.width, 0);
    path.lineTo(size.width, size.height / 2);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
7eumitmz

7eumitmz1#

笔画中心使用最后一个点在画布上绘制,您可以在定位线条时计数strokeWidth的一半。

class SeatDecorator extends CustomPainter {
  SeatDecorator({this.strokeWidth = 8});
  final double strokeWidth;
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.square
      ..style = PaintingStyle.stroke
      ..strokeJoin = StrokeJoin.round
      ..strokeWidth = strokeWidth;

    Path path = Path();
    final halfStrokeWidth = strokeWidth / 2;
    path.moveTo(-halfStrokeWidth, size.height / 2);
    path.lineTo(-halfStrokeWidth, -halfStrokeWidth);
    path.lineTo(size.width + halfStrokeWidth, -halfStrokeWidth);
    path.lineTo(size.width + halfStrokeWidth, size.height / 2);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant SeatDecorator oldDelegate) => oldDelegate.strokeWidth != strokeWidth;
}

您可以使用ShapeBorder处理此类情况。

相关问题