drawGrid method
Draw grid lines (optimized with batched operations).
Renders horizontal grid lines to help users read values from the chart. Uses batched path operations for better performance.
Parameters:
canvas- The canvas to draw onsize- The size of the chart areaminX,maxX,minY,maxY- The data bounds (used for spacing)
The grid will only be drawn if showGrid is true and the theme allows grid display. Grid lines are drawn with a semi-transparent color to avoid obscuring the chart data.
Example
drawGrid(canvas, chartSize, 0, 100, 0, 50);
Implementation
void drawGrid(
Canvas canvas,
Size size,
double minX,
double maxX,
double minY,
double maxY,
) {
if (!showGrid || !theme.showGrid) return;
// Create paint with enhanced styling (dashed/dotted look)
final gridPaint = Paint()
..color = theme.gridColor.withValues(alpha: 0.5)
..strokeWidth = 1.0
..style = PaintingStyle.stroke;
// Horizontal grid lines only (more professional)
// Pre-calculate y positions and batch draw
const horizontalLines = 5;
final lineSpacing = size.height / horizontalLines;
// Draw dashed horizontal lines
for (int i = 1; i < horizontalLines; i++) {
final y = lineSpacing * i;
_drawDashedLine(canvas, Offset(0, y), Offset(size.width, y), gridPaint);
}
// Vertical grid lines (very subtle, solid)
final verticalLines = 6;
final verticalSpacing = size.width / verticalLines;
final verticalPaint = Paint()
..color = theme.gridColor.withValues(alpha: 0.2)
..strokeWidth = 0.5
..style = PaintingStyle.stroke;
final verticalPath = Path();
for (int i = 1; i < verticalLines; i++) {
final x = verticalSpacing * i;
verticalPath.moveTo(x, 0);
verticalPath.lineTo(x, size.height);
}
canvas.drawPath(verticalPath, verticalPaint);
}