VideoView to match parent height and keep aspect ratio

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

I have a VideoView which is set up like this:



        
12条回答
  •  隐瞒了意图╮
    2020-11-28 08:33

    I have been looking for ways to display video in aspect fill in VideoView but after trying many solutions, none of them seems to work.

    So I implemented the following approach and it's working for me:

    Code:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
        // getting screen size
        ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
    
        double videoSizeRatio = (double) mVideoHeight / mVideoWidth;
        double screenSizeRatio = (double) height / width;
    
        if (mVideoWidth > 0 && mVideoHeight > 0) {
            if (videoSizeRatio > screenSizeRatio) { // screen is wider than video width
                height = (int) (videoSizeRatio * width);
            } else if (videoSizeRatio < screenSizeRatio) {
                width = (int) (height / videoSizeRatio);
            }
    
        }
        setMeasuredDimension(width, height);
    }
    

    Layout:

     
    

提交回复
热议问题