Android SurfaceView播放视频时横竖屏的调整

对于横屏录制的视频就横屏播放,对于竖屏录制的视频就竖屏播放。

在mainifest文件里对负责播放的Activity添加以下属性

 

    android:configChanges="orientation|keyboardHidden|screenSize"

 

 重写Acitivity的onConfigurationChanged方法:

 

    @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);

        }

 

根据视频的属性来区分

    @Override
        public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
            if (width == 0 || height == 0) {
                Log.e(TAG, "invalid video width(" + width + ") or height(" + height
                        + ")");
                return;
            }
            Logger.d(TAG, "onVideoSizeChanged width:" + width + " height:" + height);
            mIsVideoSizeKnown = true;
            mVideoHeight = height;
            mVideoWidth = width;
            int wid = mMediaPlayer.getVideoWidth();
            int hig = mMediaPlayer.getVideoHeight();
            // 根据视频的属性调整其显示的模式

            if (wid > hig) {
                if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else {
                if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            mSurfaceViewWidth = dm.widthPixels;
            mSurfaceViewHeight = dm.heightPixels;
            if (width > height) {
                // 竖屏录制的视频,调节其上下的空余

                int w = mSurfaceViewHeight * width / height;
                int margin = (mSurfaceViewWidth - w) / 2;
                Logger.d(TAG, "margin:" + margin);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.MATCH_PARENT);
                lp.setMargins(margin, 0, margin, 0);
                mSurfaceView.setLayoutParams(lp);
            } else {
                // 横屏录制的视频,调节其左右的空余

                int h = mSurfaceViewWidth * height / width;
                int margin = (mSurfaceViewHeight - h) / 2;
                Logger.d(TAG, "margin:" + margin);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.MATCH_PARENT);
                lp.setMargins(0, margin, 0, margin);
                mSurfaceView.setLayoutParams(lp);
            }
        }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。