devicePixelSnapOffset static method
Translation, in the canvas' current coordinate space, that moves a layer onto whole device pixels.
transform is a canvas transform matrix (Canvas.getTransform), which
maps the current space to logical pixels, and devicePixelRatio turns
those into device pixels. The result is null when the matrix is rotated
or degenerate — "device pixel alignment" has no single axis there — and
when the translation already lands on a pixel edge.
Implementation
static Vector2? devicePixelSnapOffset(
List<double> transform,
double devicePixelRatio,
) {
if (devicePixelRatio <= 0) {
return null;
}
// Column-major 4x4: [0] and [5] are the x/y scales, [1] and [4] the
// rotation/skew terms, [12] and [13] the translation.
final scaleX = transform[0];
final scaleY = transform[5];
if (scaleX == 0 || scaleY == 0) {
return null;
}
if (transform[1] != 0 || transform[4] != 0) {
return null;
}
final deviceX = transform[12] * devicePixelRatio;
final deviceY = transform[13] * devicePixelRatio;
final partialX = deviceX - deviceX.roundToDouble();
final partialY = deviceY - deviceY.roundToDouble();
if (partialX == 0 && partialY == 0) {
return null;
}
return Vector2(
-partialX / (scaleX * devicePixelRatio),
-partialY / (scaleY * devicePixelRatio),
);
}