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

如何在不使用Texture Surface且不旋转控件的情况下旋转ExoPlayer?

ExoPlayer视频旋转解决方案(无需TextureView)

针对你遇到的TextureView不兼容HDR、打乱布局的问题,以下是几个基于SurfaceView的可行方案,既能实现视频正确旋转,又不影响控件布局和HDR效果:

方案一:监听视频旋转角度,手动变换SurfaceView矩阵

  1. 给ExoPlayer添加视频尺寸变化监听器,获取视频自带的旋转角度:
player.addListener(new Player.Listener() {
    @Override
    public void onVideoSizeChanged(VideoSize videoSize) {
        int rotation = videoSize.rotationDegrees;
        applyRotationToSurfaceView(rotation);
    }
});
  1. 实现旋转变换方法,只旋转视频画面,控件布局保持不变:
private void applyRotationToSurfaceView(int rotationDegrees) {
    SurfaceView surfaceView = playerView.getVideoSurfaceView();
    Matrix matrix = new Matrix();
    float centerX = surfaceView.getWidth() / 2f;
    float centerY = surfaceView.getHeight() / 2f;
    matrix.postRotate(rotationDegrees, centerX, centerY);
    surfaceView.setTransform(matrix);
}

该方案依托SurfaceView原生支持HDR的特性,不会出现画质损失,同时控件布局不受旋转影响。

方案二:自定义RotatableSurfaceView封装旋转逻辑

如果需要更灵活的控制,可以自定义SurfaceView子类,内部封装旋转逻辑:

public class RotatableSurfaceView extends SurfaceView {
    private int rotationDegrees = 0;

    public RotatableSurfaceView(Context context) {
        super(context);
    }

    public void setVideoRotation(int degrees) {
        rotationDegrees = degrees;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        canvas.rotate(rotationDegrees, centerX, centerY);
        super.onDraw(canvas);
    }
}

在布局中替换默认SurfaceView,或通过playerView.setVideoSurfaceView()设置自定义实例,后续只需调用setVideoRotation()传入视频旋转角度即可。

方案三:动态调整PlayerView布局宽高比

当视频旋转90/270度时,宽高比会反转,可动态调整PlayerView的布局参数适配:

private void adjustPlayerViewAspectRatio(int rotationDegrees, int videoWidth, int videoHeight) {
    int adjustedWidth = videoWidth;
    int adjustedHeight = videoHeight;
    if (rotationDegrees == 90 || rotationDegrees == 270) {
        adjustedWidth = videoHeight;
        adjustedHeight = videoWidth;
    }
    playerView.setAspectRatio(adjustedWidth / (float) adjustedHeight);
}

结合方案一的旋转监听,先调整布局比例再应用矩阵旋转,能让视频完美适配容器,同时保持布局稳定。

注意事项

  • 保持PlayerView的surface_type为默认的surface_view,确保HDR正常显示。
  • 屏幕旋转时需保存当前视频旋转状态,避免Activity重建后设置丢失。
  • 直播流场景需监听旋转角度的动态变化(部分直播流可能中途变更旋转参数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:06:49