在各种设备规格上缩放媒体内容

除了传统的竖屏智能手机之外,Android 还支持各种设备规格,包括可折叠设备、平板电脑、窗口化模式环境和外接显示屏。如果您假设屏幕几何图形是静态的,媒体内容最终可能会被拉伸、剪裁或意外出现黑边。您的应用必须动态适应不断变化的显示模式下各种源媒体宽高比(从经典的 4:3 到超宽屏)。

Jetpack Compose 中的大多数媒体布局失败都源于三个常见的架构陷阱:

  • 窗口边衬区处理不一致和边到边冲突。
  • 由于窗口大小计算不正确,导致布局更新不一致。
  • 内容缩放选项配置不当。

本指南介绍了使用 Media3 和 Jetpack Compose 解决上述每个领域的策略和最佳实践。

处理窗口边衬区和无边框冲突

在搭载 Android 15(API 级别 35)及更高版本的设备上,以 API 级别 35 或更高级别为目标平台的应用默认采用边到边显示模式。系统栏(例如状态栏、导航栏和桌面标题栏)会绘制在应用内容之上,而刘海屏可能会遮挡部分内容。

如果没有适当的窗口边衬区管理,就会发生两种主要的布局冲突:

  • 系统栏重叠:视频画面、字幕和播放控件被状态栏(时钟、电池图标)、手势或导航栏或刘海屏(摄像头刘海)部分遮挡。如需了解一般设置指南,请参阅设置边到边。
  • 桌面模式标题栏干扰:在桌面窗口化模式下,系统会引入顶部标题栏,用于窗口管理。如果标准布局在渲染自定义标题或全屏媒体画布时未考虑此字幕栏,则会导致视频帧和顶部播放控件被遮挡且无法点击。如需详细了解窗口状态,请参阅支持桌面窗口化模式。
系统状态栏与全屏媒体画布和播放控件重叠。 手势导航栏与无边框媒体画布重叠。 桌面设备上的字幕栏与顶部的视频播放控件重叠。
图 1. 系统状态栏、手势导航栏和桌面标题栏与全面屏媒体画布重叠,遮挡了视频内容和播放控件。

边衬区管理策略

您的应用应根据播放器是处于非沉浸模式还是沉浸模式,动态适应系统边衬区。

非沉浸式配置

在非沉浸式播放中,系统栏会保持可见,以保留设备上下文。

当播放器延伸到窗口边缘时,对每个 PlayerDefaults 控制栏应用 windowInsetsPadding 以及 WindowInsets.safeDrawing 和 only,使其位于与系统栏或刘海屏相交的边缘(例如,TopControls 上的 Top + Horizontal 和 BottomControls 上的 Bottom + Horizontal)。这样,当视频画面延伸到整个容器时,控件就不会被系统栏遮挡。

@Composable
fun NonImmersiveVideoPlayer(
  player: Player,
  showControls: Boolean,
  modifier: Modifier = Modifier,
) {
  Player(
    player = player,
    modifier = modifier,
    showControls = showControls,
    // Keep top controls clear of the status bar, caption bar, and display cutout
    topControls = {
      PlayerDefaults.TopControls(
        player = player,
        modifier =
          Modifier.fillMaxWidth()
            .windowInsetsPadding(
              WindowInsets.safeDrawing.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal)
            ),
      ) {
        MuteButton(player = player, modifier = Modifier.align(Alignment.TopEnd).padding(16.dp))
      }
    },
    // Keep bottom controls clear of the navigation bar and display cutout
    bottomControls = {
      PlayerDefaults.BottomControls(
        player = player,
        modifier =
          Modifier.fillMaxWidth()
            .windowInsetsPadding(
              WindowInsets.safeDrawing.only(
                WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal
              )
            ),
      )
    },
  )
}

在非沉浸模式下,应用会集成窗口边衬区内边距,以动态向内移动内容。
图 2. 在非沉浸模式下,应用会应用窗口边衬区内边距,将控件向内移动。

沉浸式配置(纵向和横向)

在全屏沉浸模式下,目标是最大限度地扩大画布,以提供影院级体验,同时保持播放控件可访问:

  1. 将 windowInsetsPadding 应用于媒体控件叠加层(例如顶部和底部控件),以防止它们与刘海屏或系统手势区域重叠(例如,在底部控件上将 WindowInsets.displayCutout 与 WindowInsets.systemGestures 结合使用,使进度条不会与边缘滑动手势冲突)。
  2. 在 DisposableEffect 中使用 WindowInsetsControllerCompat 隐藏系统栏,确保在离开可组合项时恢复系统界面可见性。

@Composable
fun ImmersiveVideoPlayer(player: Player, showControls: Boolean, modifier: Modifier = Modifier) {
  val view = LocalView.current

  // Manages the system UI lifecycle to create an edge-to-edge cinematic experience
  DisposableEffect(view) {
    // Finds the hosting Activity, unwrapping any ContextWrapper around the view's context
    val activity =
      generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
        .filterIsInstance<Activity>()
        .firstOrNull()
    val window = activity?.window ?: return@DisposableEffect onDispose {}
    val controller = WindowCompat.getInsetsController(window, view)

    // Records the current system bar state so it can be restored on dispose
    val insets = ViewCompat.getRootWindowInsets(view)
    val wereSystemBarsVisible =
      insets == null ||
        insets.isVisible(WindowInsetsCompat.Type.statusBars()) ||
        insets.isVisible(WindowInsetsCompat.Type.navigationBars())
    val previousBehavior = controller.systemBarsBehavior

    // Hides status bars, navigation bars, and caption bars to maximize the video canvas
    controller.hide(WindowInsetsCompat.Type.systemBars())

    // Allows hidden system bars to temporarily reappear with a swipe gesture from the edge
    controller.systemBarsBehavior =
      WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE

    onDispose {
      // Restores the previous system bar state when leaving the composable
      controller.systemBarsBehavior = previousBehavior
      if (wereSystemBarsVisible) {
        controller.show(WindowInsetsCompat.Type.systemBars())
      }
    }
  }

  Player(
    player = player,
    modifier = modifier,
    showControls = showControls,
    // Keep top controls clear of the display cutout while the system bars are hidden
    topControls = {
      PlayerDefaults.TopControls(
        player = player,
        modifier =
          Modifier.fillMaxWidth()
            .windowInsetsPadding(
              WindowInsets.displayCutout.only(
                WindowInsetsSides.Top + WindowInsetsSides.Horizontal
              )
            ),
      ) {
        MuteButton(player = player, modifier = Modifier.align(Alignment.TopEnd).padding(16.dp))
      }
    },
    // Keep bottom controls clear of the display cutout and system gesture areas
    bottomControls = {
      PlayerDefaults.BottomControls(
        player = player,
        modifier =
          Modifier.fillMaxWidth()
            .windowInsetsPadding(
              WindowInsets.displayCutout
                .union(WindowInsets.systemGestures)
                .only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal)
            ),
      )
    },
  )
}

当视频播放器进入沉浸模式时,系统栏会自动隐藏,从而提供全屏影院级体验。
图 3. 当视频播放器进入沉浸模式时,系统栏会隐藏。

计算动态窗口大小调整和布局更新

如果仅在应用启动时计算一次屏幕宽度或高度,会导致布局在设备配置发生变化(例如可折叠设备展开、多窗口模式会话调整大小或屏幕旋转)时依赖于过时的值。

在这些情况下,即使子组件正确使用 Modifier.fillMaxWidth(),如果其父容器受到过时尺寸的限制,它也无法自适应,从而导致拉伸、剪裁或布局无响应。

在以下示例中,左侧画面展示了在标准视口中的正确呈现效果,而右侧画面则展示了在设备展开时,过时的窗口尺寸无法自适应,导致内容布局无法响应。

在标准视口上正确呈现,并动态适应宽高比。 设备展开时,过时的窗口尺寸无法适应。
图 4. 动态宽高比自适应对比。

为避免布局限制条件过时,请使用 Jetpack Media Query API。由于此 API 处于实验阶段且默认处于停用状态,因此请先通过设置 ComposeUiFlags.isMediaQueryIntegrationEnabled = true(例如,在调用 setContent 之前)启用 mediaQuery 函数,然后使用 @OptIn(ExperimentalMediaQueryApi::class) 选择启用。

使用 derivedMediaQuery 评估当前窗口大小的条件(例如 windowWidth),以便在窗口发生变化时更新布局,而无需进行不必要的重组。您可以将 derivedMediaQuery 与 WindowSizeClass 断点结合使用,以便在窗口展开时在单窗格和多窗格播放器布局之间切换:

@OptIn(ExperimentalMediaQueryApi::class)
@Composable
fun AdaptiveVideoPlayerScreen(
  player: Player,
  modifier: Modifier = Modifier,
  relatedContent: @Composable () -> Unit,
) {
  val isWideWindow by derivedMediaQuery {
    windowWidth >= WindowSizeClass.WIDTH_DP_MEDIUM_LOWER_BOUND.dp
  }

  if (isWideWindow) {
    // Medium or expanded width: place the player alongside a details or playlist pane
    Row(modifier = modifier.fillMaxSize()) {
      Player(player = player, modifier = Modifier.weight(0.65f).fillMaxHeight())
      Box(modifier = Modifier.weight(0.35f).fillMaxHeight()) { relatedContent() }
    }
  } else {
    // Compact width: stack a 16:9 player above the details pane
    Column(modifier = modifier.fillMaxSize()) {
      Player(player = player, modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f))
      Box(modifier = Modifier.weight(1f).fillMaxWidth()) { relatedContent() }
    }
  }
}

配置内容缩放和宽高比

区分管理可用容器区域和缩放媒体内容本身。使用边衬区管理(例如安全区域内边距)来设置相对于系统栏和刘海屏的容器边界。然后在这些边界内应用扩缩策略。如需了解如何构建容器和跨宽高比缩放视觉内容,请参阅内容组合和结构。

在以下示例中,左侧图片展示了在需要完全可见时,剪裁策略如何截断内容,而右侧图片展示了自适应策略如何保留原生宽高比以进行全帧渲染。

在需要完整显示内容时,剪裁策略导致大量内容丢失。 保持原生宽高比以进行全帧渲染的适配策略。
图 5. 扩缩行为比较。

Media3 组件会自动处理标准视频宽高比,但在使用自定义 Compose 布局或受限容器(例如可滚动的社交动态)时,显式 ContentScale 配置至关重要。选择不当的内容缩放比例可能会导致布局问题,例如视频失真(拉伸)或意外出现黑边,从而在视口中留下空白。在没有这些选项的情况下手动管理视频 Surface,也可能会导致在屏幕旋转或可折叠设备状态发生变化时布局损坏。

无论是 16:9 的视频在 4:3 的屏幕上显示,还是 4:3 的视频在 16:9 的屏幕上显示,Player 可组合项都会默认使用 ContentScale.Fit。这样可以应用信箱模式或邮筒模式,从而使整个视频保持可见,而不会被剪裁。

后续显示模式更改(例如缩放或剪裁)应由用户驱动。例如,切换到 ContentScale.Crop 以完全填充容器。交互式缩放切换开关可平衡布局要求与用户选择。

实施示例

您可以使用标准 Compose ContentScale 属性强制执行全帧可见性并处理宽高比。

使用 Player 可组合项

最简单、最直接的方法是使用 Player 可组合项。它作为一个高级封装容器,可自动处理缩放边界,将用于视频渲染的 ContentFrame 与可自定义的控件叠加层(topControls、centerControls、bottomControls)和快门层配对:

@Composable
fun FitVideoPlayer(player: Player, modifier: Modifier = Modifier) {
  Player(
    player = player,
    modifier = modifier.fillMaxSize(), // Fill the available space
    contentScale = ContentScale.Fit, // Default; shown for clarity
  )
}

构建自定义视频播放器布局或直接在视频流上放置自定义界面层时,您可以直接使用 ContentFrame 进行精确的底层布局控制。

动态用户控制的缩放切换开关

为了提升应用的观看体验,您可以添加一个可选切换开关,以便在不同的内容缩放选项之间切换。通过检测双击手势,您可以立即在 ContentScale.Fit 和 ContentScale.Crop 之间切换播放器的状态。您还可以扩展此功能,以支持使用双指张合缩放或其他多点触控手势进行动态 ContentScale 调整,类似于现代视频在线播放应用。

图 6. 在 ContentScale.Fit 和 ContentScale.Crop 之间切换。

@Composable
fun ZoomableVideoPlayer(player: Player, modifier: Modifier = Modifier) {
  var isCropped by rememberSaveable { mutableStateOf(false) }

  Player(
    player = player,
    modifier =
      modifier
        .fillMaxSize()
        // Handle double-tap to toggle between Fit and Crop scaling
        .pointerInput(Unit) { detectTapGestures(onDoubleTap = { isCropped = !isCropped }) },
    contentScale = if (isCropped) ContentScale.Crop else ContentScale.Fit,
  )
}

虽然有多种内容缩放选项,但请根据您的应用场景选择缩放选项:对于短视频或可滚动信息流,如果主要目标是填满屏幕,请使用 ContentScale.Crop;对于包含重要边距信息(例如体育赛事比分或字幕)的媒体,请默认使用 ContentScale.Fit,以保护重要的视觉背景信息。