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
final gridPaint = Paint()
..color = theme.gridColor.withValues(alpha: 0.4)
..strokeWidth = 0.8
..style = PaintingStyle.stroke;
// Horizontal grid lines only (more professional)
// Pre-calculate y positions and batch draw
const horizontalLines = 5;
final lineSpacing = size.height / horizontalLines;
final path = Path();
for (int i = 1; i < horizontalLines; i++) {
final y = lineSpacing * i;
path.moveTo(0, y);
path.lineTo(size.width, y);
}
canvas.drawPath(path, gridPaint);
// Add subtle vertical grid lines for better readability
final verticalLines = 6;
final verticalSpacing = size.width / verticalLines;
final verticalPath = Path();
final verticalPaint = Paint()
..color = theme.gridColor.withValues(alpha: 0.2)
..strokeWidth = 0.5
..style = PaintingStyle.stroke;
for (int i = 1; i < verticalLines; i++) {
final x = verticalSpacing * i;
verticalPath.moveTo(x, 0);
verticalPath.lineTo(x, size.height);
}
canvas.drawPath(verticalPath, verticalPaint);
}