fillShape function

Image fillShape(
  1. Image dst,
  2. List<List<int>> vertices,
  3. int col
)

Fills an arbitrary polygon with col in dst.

The vertices of this polygon are given by vertices, where each element should be a list containing a pair of x-y coordinates.

Implementation

Image fillShape(Image dst, List<List<int>> vertices, int col) {
  if (vertices.first[0] != vertices.last[0] ||
      vertices.first[1] != vertices.last[1]) {
    vertices.add(vertices.first);
  }

  bool isInsideShape(int x, int y) {
    bool inside = false;

    for (int i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {
      if ((vertices[i][1] > y) != (vertices[j][1] > y) &&
          x <
              (vertices[j][0] - vertices[i][0]) *
                      (y - vertices[i][1]) /
                      (vertices[j][1] - vertices[i][1]) +
                  vertices[i][0]) {
        inside = !inside;
      }
    }
    return inside;
  }

  int minX = vertices.first[0];
  int maxX = vertices.first[0];
  int minY = vertices.first[1];
  int maxY = vertices.first[1];

  for (final vertex in vertices) {
    minX = min(minX, vertex[0]);
    maxX = max(maxX, vertex[0]);
    minY = min(minY, vertex[1]);
    maxY = max(maxY, vertex[1]);
  }

  for (int x = minX; x < maxX; x++) {
    for (int y = minY; y < maxY; y++) {
      if (isInsideShape(x, y)) {
        dst.setPixelSafe(x, y, alphaBlendColors(dst.getPixelSafe(x, y), col));
      }
    }
  }

  return dst;
}