如何在子父尺寸相同时将坐标转换为Flutter的Alignment?
子组件与父容器尺寸相同时,如何计算正确的Flutter Alignment值
我正在尝试将父容器中子组件的像素坐标(x、y)转换为Flutter的Alignment对应的x、y值。参考Flutter自带的Alignment.inscribe方法,我编写了如下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)); }
对比Flutter原生的Alignment.inscribe 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, ); }
当前代码存在边缘场景问题:当子组件尺寸与父容器完全相同时,会返回0值(如果没有判断逻辑则会出现无穷大/NaN)。但实际场景中,即使两者尺寸一致,我们也应该能得到正确的对齐值——比如下面两种场景:

VS

当前这种场景下,y轴的Alignment值会被强制设为0,但从坐标空间来看,其实可以计算出正确的对齐结果。想请教有没有方法解决这个问题?
内容的提问来源于stack exchange,提问作者Saad Ardati
相关产品推荐
相关产品推荐

