VideoView to match parent height and keep aspect ratio

前端 未结 12 1932
轻奢々
轻奢々 2020-11-28 08:15

I have a VideoView which is set up like this:



        
12条回答
  •  时光说笑
    2020-11-28 08:36

    You should extends from the built-in video view.

    Call setVideoSize before video view is shown, you can get video size from thumbnail extracted from video.

    So that, when video view's onMeasure is called, both mVideoWidth & mVideoHeight are > 0.

    If you want to account the height of controllers, you can do it yourself in the onMeasure method.

    Hope will help.

    public class MyVideoView extends VideoView {
    
            private int mVideoWidth;
            private int mVideoHeight;
    
            public MyVideoView(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
    
            public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
    
            public MyVideoView(Context context) {
                super(context);
            }
    
            public void setVideoSize(int width, int height) {
                mVideoWidth = width;
                mVideoHeight = height;
            }
    
            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                // Log.i("@@@", "onMeasure");
                int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
                int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
                if (mVideoWidth > 0 && mVideoHeight > 0) {
                    if (mVideoWidth * height > width * mVideoHeight) {
                        // Log.i("@@@", "image too tall, correcting");
                        height = width * mVideoHeight / mVideoWidth;
                    } else if (mVideoWidth * height < width * mVideoHeight) {
                        // Log.i("@@@", "image too wide, correcting");
                        width = height * mVideoWidth / mVideoHeight;
                    } else {
                        // Log.i("@@@", "aspect ratio is correct: " +
                        // width+"/"+height+"="+
                        // mVideoWidth+"/"+mVideoHeight);
                    }
                }
                // Log.i("@@@", "setting size: " + width + 'x' + height);
                setMeasuredDimension(width, height);
            }
    }
    

提交回复
热议问题