Flutter如何实现坐标网格图标

在Flutter中如何绘制一个带坐标网格的图表?我想实现类似Excel那样的网格背景,上面可以叠加折线图或散点图。目前尝试了CustomPaint但网格线的间距和样式控制不太灵活,有没有更好的实现方案?最好能支持动态调整网格密度和自定义轴线样式。

2 回复

在Flutter中,可通过CustomPaint自定义绘制网格图标。使用CanvasdrawLine方法绘制水平和垂直线条,设置间距和颜色即可实现坐标网格。

更多关于Flutter如何实现坐标网格图标的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现坐标网格图标可以通过以下几种方式:

1. 使用CustomPaint自定义绘制

import 'package:flutter/material.dart';

class GridIcon extends StatelessWidget {
  final double size;
  final Color color;
  
  const GridIcon({super.key, this.size = 24, this.color = Colors.black});
  
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: _GridIconPainter(color: color),
    );
  }
}

class _GridIconPainter extends CustomPainter {
  final Color color;
  
  _GridIconPainter({required this.color});
  
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke;
    
    final double step = size.width / 3;
    
    // 绘制垂直线
    for (int i = 1; i < 3; i++) {
      canvas.drawLine(
        Offset(i * step, 0),
        Offset(i * step, size.height),
        paint,
      );
    }
    
    // 绘制水平线
    for (int i = 1; i < 3; i++) {
      canvas.drawLine(
        Offset(0, i * step),
        Offset(size.width, i * step),
        paint,
      );
    }
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

// 使用方式
GridIcon(size: 24, color: Colors.blue)

2. 使用Stack和Container组合

Widget buildGridIcon() {
  return Container(
    width: 24,
    height: 24,
    decoration: BoxDecoration(
      border: Border.all(color: Colors.black, width: 1),
    ),
    child: Stack(
      children: [
        // 垂直线
        Positioned(left: 8, top: 0, bottom: 0, child: Container(width: 1, color: Colors.black)),
        Positioned(left: 16, top: 0, bottom: 0, child: Container(width: 1, color: Colors.black)),
        // 水平线
        Positioned(left: 0, top: 8, right: 0, child: Container(height: 1, color: Colors.black)),
        Positioned(left: 0, top: 16, right: 0, child: Container(height: 1, color: Colors.black)),
      ],
    ),
  );
}

3. 使用SVG图标(推荐)

如果项目支持,可以使用SVG文件:

import 'package:flutter_svg/flutter_svg.dart';

SvgPicture.asset(
  'assets/grid_icon.svg',
  width: 24,
  height: 24,
  color: Colors.black,
)

推荐使用CustomPaint方式,因为它提供了最好的灵活性和性能,可以轻松调整网格大小、颜色和线条粗细。

回到顶部