autoGrid method

Future<void> autoGrid(
  1. Image image
)

Implementation

Future<void> autoGrid(Image image) async{
  //Image img = image;
  final Image img = await getImage(image);
  final ByteData? byteData = await img.toByteData();
  final Uint8List pixels = byteData!.buffer.asUint8List();
  List<Rect> startingRect = [];
  TileGrid? newGrids;

  bool start = false;
  int iStart = 0;

  for(int i = 0; i < img.height;i++){
    bool allZeros = true;
    for (int j = 0; j < img.width;j++){
      Color color = Color.fromARGB(pixels[j*4+i*img.width*4], pixels[(j*4+i*img.width*4)+1], pixels[(j*4+i*img.width*4)+2], pixels[(j*4+i*img.width*4)+3]);
      if(color != const Color.fromARGB(0,0,0,0)){
        allZeros = false;
        if(!start){
          start = true;
          iStart = i;
        }
        break;
      }
    }

    if((allZeros && start) || (i == img.height-1 && start)){
      start = false;
      startingRect.add(Rect.fromLTWH(0,iStart.toDouble(),img.width.toDouble(),(i-iStart).toDouble()));
    }
  }

  start = false;

  for(int k = 0; k < startingRect.length; k++){
    int height = startingRect[k].height.toInt();
    int width = startingRect[k].width.toInt();
    int x = 0;

    for(int i = 0; i < width;i++){
      bool allZeros = true;

      for (int j = startingRect[k].top.toInt();j < startingRect[k].top+height; j++){
        Color color = Color.fromARGB(pixels[j*width*4+i*4], pixels[(j*width*4+i*4)+1], pixels[(j*width*4+i*4)+2], pixels[(j*width*4+i*4)+3]);

        if(color != const Color.fromARGB(0,0,0,0)){
          allZeros = false;
          if(!start){
            start = true;
            x = i;
          }
          break;
        }
      }

      if((allZeros && start) || (i == width-1 && start)){
        start = false;
        Rect rects = Rect.fromLTWH(x.toDouble(), startingRect[k].top,(i-x).toDouble(),height.toDouble());
        x = i;

        Vector3 newPosition = position+
        Converter.toVector3(Vector3(0,0,0), Offset(rects.left.toDouble(),rects.top.toDouble()));

        if(newGrids == null){
          newGrids = TileGrid(
            rects: [rects],
            position: [newPosition],
            type: GridType.auto
          );
        }
        else{
          newGrids.rects.add(rects);
          newGrids.position.add(
            newPosition
          );
        }
      }
    }
  }
  grid = newGrids!;
  grid.generateCollisions(newGrids.rects.length);
}