Flutter中使用Transform.scale缩放至0.5时子组件为什么会被裁剪?
问题原因
Transform.scale 仅会修改组件的绘制效果,不会改变组件本身的布局尺寸,你原本的场景组件尺寸大于横屏状态下的屏幕尺寸,缩放后布局尺寸仍保持原始大小,超出屏幕的部分就会被父容器自动裁剪。
解决方案
方案1(更推荐,无需手动计算缩放比例)
使用 FittedBox 组件自动完成适配,可保证内容按比例缩放的同时不会被裁剪:
Widget scene() { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; final bool isLandscape = width > height; return SizedBox( // 外层容器撑满需要展示场景的屏幕区域 width: width, height: height, child: FittedBox( // BoxFit.contain规则会自动缩放内容,保证完整展示无裁剪 fit: BoxFit.contain, // 对齐方式可按需调整,这里设为顶部中心匹配你原有的顶部定位逻辑 alignment: isLandscape ? Alignment.topCenter : Alignment.center, child: Stack( children: [ Positioned(top: 0, width: 150, child: HillVehicleAnimation()), // 其余子组件 ], ), ), ); }
方案2(保留手动控制scale逻辑)
如果需要自定义缩放数值,只需给Transform.scale外层套一个匹配缩放后尺寸的容器,同时调整缩放原点即可:
Widget scene() { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; final bool isLandscape = width > height; final double scale = isLandscape ? 0.5 : 1; // 此处替换为你的场景实际原始宽高 const double sceneOriginalWidth = 750; const double sceneOriginalHeight = 1334; return SizedBox( width: sceneOriginalWidth * scale, height: sceneOriginalHeight * scale, child: Transform.scale( scale: scale, // 缩放原点设为顶部中心,避免内容偏移 alignment: Alignment.topCenter, child: Stack( children: [ Positioned(top: 0, width: 150, child: HillVehicleAnimation()), // 其余子组件 ], ), ), ); }
内容的提问来源于stack exchange,提问作者Stéphane de Luca
相关产品推荐
相关产品推荐

