Flutter 使用 DecoratedBox 绘制dash line

59 min read

Flutter可以通过绘制一个自定义的DecorationBox来实现虚线的绘制。在DecorationBox中,我们可以定义各种装饰元素,例如背景、边框等等。为了绘制虚线,我们需要定义一个自定义的Painter,在Painter中实现虚线的绘制逻辑。

以下是绘制虚线的示例代码:

import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class DashedLinePainter extends CustomPainter {
  final double strokeWidth;
  final Color color;
  final StrokeCap strokeCap;
  final double gapWidth;
  final double dashWidth;

  DashedLinePainter({
    this.color = Colors.black,
    this.strokeWidth = 1.0,
    this.strokeCap = StrokeCap.square,
    this.gapWidth = 5,
    this.dashWidth = 10,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..strokeCap = strokeCap;

    final double x1 = 0.0;
    final double y1 = size.height / 2;
    final double x2 = size.width;
    final double y2 = y1;

    final Path path = Path()
      ..moveTo(x1, y1)
      ..lineTo(x2, y2);

    final List<double> dashArray = <double>[dashWidth, gapWidth];

    paint..shader = ui.Gradient.linear(
      Offset.zero,
      const Offset(10, 10),
      [Colors.white54, color, color])
      ..strokeWidth = strokeWidth
      ..strokeCap = strokeCap
      ..style = PaintingStyle.stroke;

    canvas.drawPath(
      dashPath(
        path,
        dashArray: CircularIntervalList<double>(dashArray),
      ),
      paint,
    );
  }

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

class DashedLine extends StatelessWidget {
  final double strokeWidth;
  final Color color;
  final StrokeCap strokeCap;
  final double gapWidth;
  final double dashWidth;
  final double height;
  final double width;

  DashedLine({
    this.color = Colors.black,
    this.strokeWidth = 1.0,
    this.strokeCap = StrokeCap.square,
    this.gapWidth = 5,
    this.dashWidth = 10,
    this.width = double.maxFinite,
    this.height = 1,
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: DashedLinePainter(
        color: color,
        strokeWidth: strokeWidth,
        strokeCap: strokeCap,
        gapWidth: gapWidth,
        dashWidth: dashWidth,
      ),
      size: Size(width, height),
    );
  }
}

使用示例:

DashedLine(
  color: Colors.black54,
  strokeWidth: 1,
  gapWidth: 4,
  dashWidth: 6,
  height: 1,
),

在DashedLinePainter中,我们定义了color、strokeWidth、strokeCap、gapWidth和dashWidth等属性,它们分别表示虚线的颜色、宽度、末端样式、虚线间隔宽度和虚线宽度。在paint方法中,我们通过自定义的dashPath方法生成虚线路径,并使用drawPath方法绘制虚线。在DashedLine中,我们将自定义的DashedLinePainter作为CustomPaint的painter属性,来将虚线绘制出来。