I'm trying to convert pixel-based x and y values of a child inside a parent such to Flutter's Alignment x & y.
This code is adapted and inspired by Flutter's own Alignment.inscribe
function:
(typescript)
function convertPositionToAlignment(
parentWidth: number,
parentHeight: number,
childX: number,
childY: number,
childWidth: number,
childHeight: number
): AlignmentModel {
const halfWidthDelta = (parentWidth - childWidth) / 2;
const halfHeightDelta = (parentHeight - childHeight) / 2;
let x;
if (halfWidthDelta != 0) {
x = (childX - halfWidthDelta) / halfWidthDelta;
} else {
x = 0;
}
let y;
if (halfHeightDelta != 0) {
y = (childY - halfHeightDelta) / halfHeightDelta;
} else {
y = 0;
}
return new AlignmentModel(new AlignmentData(x, y));
}
In contrast, here's Flutter's Alignment.inscribe
function:
(dart)
/// Returns a rect of the given size, aligned within given rect as specified
/// by this alignment.
///
/// For example, a 100×100 size inscribed on a 200×200 rect using
/// [Alignment.topLeft] would be the 100×100 rect at the top left of
/// the 200×200 rect.
Rect inscribe(Size size, Rect rect) {
final double halfWidthDelta = (rect.width - size.width) / 2.0;
final double halfHeightDelta = (rect.height - size.height) / 2.0;
return Rect.fromLTWH(
rect.left + halfWidthDelta + x * halfWidthDelta,
rect.top + halfHeightDelta + y * halfHeightDelta,
size.width,
size.height,
);
}
The code is simple, but there is a single issue with it which is the edge-case where if the child's size is equal to the parent's, then this produces values of zero (it would produce infinite/NaN otherwise without the if statements).
I was wondering if there's any way to calculate the alignment if the sizes happen to be the same. This is not an issue with coordinate spaces, but is when it comes to alignment.
The reason we would want such an edge-case done away with is for cases like so:
VERSUS:
This edge case where the image is the same size as the container's box will cause a y alignment of zero right now when it is easily possible in the coordinate space.