s2q method

Size s2q(
  1. double dimension, {
  2. bool translate = true,
  3. bool clip = true,
})

NOTE: Yanked from Funvas Scales the canvas to a square with side lengths of dimension.

Additionally, translate the canvas, so that the square is centered (in case the original size does not have an aspect ratio of 1. This means that dimensions will not be distorted (pixel aspect ratio will stay the same) and instead, there will be unused space in case the original dimensions had a different aspect ratio than 1. Furthermore, to ensure the square effect, the square will be clipped.

The translation and clipping can also be turned off by passing translate and clip as false.

Returns the scaled width and height as a Size. If translate is true, the returned size will be a square of the given dimension. Otherwise, the returned size might have one side that is larger.

Use cases

This method is useful if you know that you will be designing a funvas for certain dimensions. This way, you can use fixed values for all sizes in the animation and when the funvas is displayed in different dimensions, your fixed dimensions still work.

I use this a lot because I know what dimensions I want to have for the GIF that I will be posting to Twitter beforehand.

Notes

"s2q" stands for "scale to square". I decided to not use "s2s" because it sounded a bit weird.


My usage recommendation is the following:

final s = s2q(750), w = s.width, h = s.height;

You could of course simply use a single variable for the dimensions since w and h will be equal for a square. However, using my way will allow you to stay flexible. You could simply disable translate later on and/or use a different aspect ratio :)

Implementation

Size s2q(
  double dimension, {
  bool translate = true,
  bool clip = true,
}) {
  final shortestSide = min(x.width, x.height);
  if (translate) {
    // Center the square.
    c.translate((x.width - shortestSide) / 2, (x.height - shortestSide) / 2);
  }

  final scaling = shortestSide / dimension;
  c.scale(scaling);
  final scaledSize = translate
      ? Size.square(dimension)
      : Size(x.width / scaling, x.height / scaling);

  if (clip) {
    c.clipRect(Offset.zero & scaledSize);
  }

  return scaledSize;
}