So I have extended VideoView's onMeasure to scale up the video to fit inside a fullscreen view.
here is how:
public void setVideoAspect(int w,int h){
wVideo=w;
hVideo=h;
onMeasure(w, h);
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(wVideo!=0 && hVideo!=0)
setMeasuredDimension(wVideo,hVideo);
}
I call setVideoAspect() with the display metrics (width, hight) of the screen. The problem is that this method stretches the video to fit inside the screen. I want to be able to keep the aspect ratio. (I have 4:3 video and 3:2 screen size.) I used the folowing code to give the retained ratio measurements to the view:
int height = (int) (metrics.widthPixels*3/(float)4);
int width= metrics.widthPixels;
mVideoView.setVideoAspect(width,height);
So this does the job but there is an issue: it gives me a 4:3 video with the width of the screen and scales the height correctly, but it doesn't center the video. (It just crops the bottom part of the video instead of the top and the bottom equally.) I have a relative layout containing the VideoView with the gravity of the VideoView set to center.
In order to center the video in the RelativeLayout I added both
layout_gravity="center"
adlayout_centerInParent="true"
. It works on my Android 4.3 phone.This works for any video keeping the video's aspect ratio. It positions the video inside the VideoView and performs a Center Crop or a Center Inside just like an ImageView.
I am using a VideoView to cover the whole ConstraintLayout. You can use any other layout probably with match_parent as width and height.
In onCreate:
Hope it helps someone!
Cameron's Answer in a programmatic way(in case someone like me needs it) This code is inside onCreate of an activity in my code( 'this' below refers to the activity)
Try using a FrameLayout instead. I'm not sure why, but if I use a Linear or Relative in my code it won't center, but Frame does. Here is the XML that fit my video to the screen, preserving the ratio and centering it: