expressiveCustomPolygon function

ExpressiveRoundedPolygon expressiveCustomPolygon({
  1. required int reps,
  2. required double centerX,
  3. required double centerY,
  4. required bool mirroring,
  5. required List<ExpressivePointNRound> points,
})

MaterialShapes.customPolygon: points repeated reps times around (centerX, centerY) — or, mirroring, 2 × reps times, every other section mirrored — as a polygon centred there (doRepeat).

Implementation

ExpressiveRoundedPolygon expressiveCustomPolygon({
  required int reps,
  required double centerX,
  required double centerY,
  required bool mirroring,
  required List<ExpressivePointNRound> points,
}) {
  final vertices = <double>[];
  final rounding = <ExpressiveCornerRounding>[];
  void add(double x, double y, ExpressiveCornerRounding r) {
    vertices
      ..add(x)
      ..add(y);
    rounding.add(r);
  }

  if (mirroring) {
    final angles = [
      for (final p in points) _angleDegrees(p.x - centerX, p.y - centerY),
    ];
    final distances = [
      for (final p in points)
        math.sqrt(
          (p.x - centerX) * (p.x - centerX) + (p.y - centerY) * (p.y - centerY),
        ),
    ];
    final actualReps = reps * 2;
    final sectionAngle = 360 / actualReps;
    for (var it = 0; it < actualReps; it++) {
      for (var index = 0; index < points.length; index++) {
        final i = it.isEven ? index : points.length - 1 - index;
        if (i > 0 || it.isEven) {
          final a = _toRadians(
            sectionAngle * it +
                (it.isEven
                    ? angles[i]
                    : sectionAngle - angles[i] + 2 * angles[0]),
          );
          add(
            math.cos(a) * distances[i] + centerX,
            math.sin(a) * distances[i] + centerY,
            points[i].rounding,
          );
        }
      }
    }
  } else {
    final np = points.length;
    for (var it = 0; it < np * reps; it++) {
      final p = points[it % np];
      final a = _toRadians((it ~/ np) * 360 / reps);
      final ox = p.x - centerX;
      final oy = p.y - centerY;
      add(
        ox * math.cos(a) - oy * math.sin(a) + centerX,
        ox * math.sin(a) + oy * math.cos(a) + centerY,
        p.rounding,
      );
    }
  }
  return ExpressiveRoundedPolygon.fromVertices(
    vertices,
    perVertexRounding: rounding,
    centerX: centerX,
    centerY: centerY,
  );
}