You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter技术问题:如何按比例缩放视频至全屏且无白边

解决方案:用FittedBox实现视频全屏裁剪填充

你的核心需求是让视频保持宽高比填充全屏、消除白边、允许裁剪溢出,不用手动计算缩放比例,Flutter的FittedBox配合BoxFit.cover就能完美解决这个问题,适配所有设备。

原代码的问题

  • 用window.physicalSize(物理像素)计算缩放,正确应该用MediaQuery获取的逻辑像素,物理像素受设备像素比影响,会导致缩放比例计算偏差。
  • Center组件会让缩放后的视频居中,但未处理溢出部分,手动计算缩放容易出现适配漏洞。
  • 没必要自己写getScale(),Flutter布局组件已封装这类逻辑。

修改后的代码

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: _controller.value.isInitialized
        ? ClipRect( // 裁剪超出屏幕的视频部分
            child: FittedBox(
              fit: BoxFit.cover, // 保持宽高比填充容器,超出部分自动裁剪
              child: SizedBox(
                width: _controller.value.size.width,
                height: _controller.value.size.height,
                child: GestureDetector(
                  onTap: tappedVideo,
                  child: VideoPlayer(_controller),
                ),
              ),
            ),
          )
        : errorPlayback
            ? const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error),
                    Text("Sorry, can't load the video :("),
                  ],
                ),
              )
            : const Center(child: CircularProgressIndicator()),
    floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    floatingActionButton: playerControls(),
  );
}

代码说明

  • BoxFit.cover会自动计算合适的缩放比例,让视频填满父容器,同时保持原宽高比,超出屏幕的部分会被裁剪。
  • ClipRect确保溢出的视频部分被截断,不会显示在屏幕外。
  • 依赖Scaffold的body默认占满屏幕的特性,无需手动获取屏幕尺寸,简化逻辑。
  • 移除了手动计算缩放的getScale()方法,避免适配错误。

内容的提问来源于stack exchange,提问作者Harmen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:55:12