dashed_line_painter.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'package:flutter/material.dart';
  2. class VerticalDashedLine extends StatelessWidget {
  3. final double height; // 虚线总高度
  4. final Color color; // 颜色
  5. final double strokeWidth; // 线条粗细
  6. final double dashLength; // 虚线线段长度
  7. final double dashSpace; // 虚线间隔长度
  8. const VerticalDashedLine({
  9. this.height = 100,
  10. this.color = Colors.grey,
  11. this.strokeWidth = 1,
  12. this.dashLength = 5,
  13. this.dashSpace = 3,
  14. super.key,
  15. });
  16. @override
  17. Widget build(BuildContext context) {
  18. return CustomPaint(
  19. size: Size(strokeWidth, height), // 宽度为线条粗细,高度为总高度
  20. painter: _VerticalDashedLinePainter(
  21. color: color,
  22. strokeWidth: strokeWidth,
  23. dashLength: dashLength,
  24. dashSpace: dashSpace,
  25. ),
  26. );
  27. }
  28. }
  29. class _VerticalDashedLinePainter extends CustomPainter {
  30. final Color color;
  31. final double strokeWidth;
  32. final double dashLength;
  33. final double dashSpace;
  34. _VerticalDashedLinePainter({
  35. required this.color,
  36. required this.strokeWidth,
  37. required this.dashLength,
  38. required this.dashSpace,
  39. });
  40. @override
  41. void paint(Canvas canvas, Size size) {
  42. final paint = Paint()
  43. ..color = color
  44. ..strokeWidth = strokeWidth
  45. ..style = PaintingStyle.stroke;
  46. double startY = 0;
  47. while (startY < size.height) {
  48. // 绘制垂直方向的虚线线段
  49. canvas.drawLine(
  50. Offset(0, startY), // 起点 (x=0, y=startY)
  51. Offset(0, startY + dashLength), // 终点 (x=0, y=startY+dashLength)
  52. paint,
  53. );
  54. startY += dashLength + dashSpace;
  55. }
  56. }
  57. @override
  58. bool shouldRepaint(CustomPainter oldDelegate) => false;
  59. }