import 'package:flutter/material.dart';

/// 绘制背景方格
/// 入参：xGridNums X轴方格数
/// 入参：yGridNums y轴方格数
class GridBackgroundPainter extends CustomPainter {
  final int xGridNums;

  GridBackgroundPainter(this.xGridNums);

  @override
  void paint(Canvas canvas, Size size) {
    final gridPaint = Paint()
      ..color = Colors.grey.withOpacity(0.5)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0;

    final double xGridSize = size.width / xGridNums;
    final double yGridSize = xGridSize;
    final int yGridNums = (size.height / yGridSize).ceil();

    final double centerY = size.height / 2;

    for (int i = 0; i < xGridNums; i++) {
      final offsetX = i * xGridSize;
      canvas.drawLine(
        Offset(offsetX, 0),
        Offset(offsetX, size.height),
        gridPaint,
      );
    }

    for (int i = 0; i < yGridNums / 2; i++) {
      final offsetY = (i * yGridSize);
      canvas.drawLine(
        Offset(0, centerY + offsetY),
        Offset(size.width, centerY + offsetY),
        gridPaint,
      );
      canvas.drawLine(
        Offset(0, centerY - offsetY),
        Offset(size.width, centerY - offsetY),
        gridPaint,
      );
    }

    ///最后一根线往上移半个像素
    // canvas.drawLine(
    //   Offset(0, size.height - 0.5),
    //   Offset(size.width, size.height - 0.5),
    //   gridPaint,
    // );
    canvas.drawLine(
      Offset(size.width - 0.5, 0),
      Offset(size.width - 0.5, size.height),
      gridPaint,
    );

    /// 绘制两根中心线
    final centerLinePaint = Paint()
      ..color = const Color.fromARGB(255, 1, 4, 148)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0;
    canvas.drawLine(
      Offset(0, size.height / 2),
      Offset(size.width, size.height / 2),
      centerLinePaint,
    );
  }

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