Center Crop an Android VideoView - android

I am looking for something like the CENTER_CROP in ImageView.ScaleType
Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view. From XML, use this syntax: android:scaleType="centerCrop"
but for a VideoView. Does anything like this exist?

You can only achieve this with a TextureView. (surfaceView won't work either). Here's a lib for playing video in a textureView with center crop function. TextureView can only be used in api level 14 and up unfortunately.
https://github.com/dmytrodanylyk/android-video-crop
Another possibility is to zoom in the videoview just right, but I haven't tried that yet.

The simple and easy way if you are using ConstraintLayout.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="#dimen/dimen_0dp"
android:layout_height="#dimen/dimen_0dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
then
In Kotlin:
videoView.setOnPreparedListener { mediaPlayer ->
val videoRatio = mediaPlayer.videoWidth / mediaPlayer.videoHeight.toFloat()
val screenRatio = videoView.width / videoView.height.toFloat()
val scaleX = videoRatio / screenRatio
if (scaleX >= 1f) {
videoView.scaleX = scaleX
} else {
videoView.scaleY = 1f / scaleX
}
}
See my Java version answer here:
https://stackoverflow.com/a/59069357/6255841
And this worked for me.

Nabin's answer worked for me.
Here is the Java version:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
float screenRatio = videoView.getWidth() / (float) videoView.getHeight();
float scaleX = videoRatio / screenRatio;
if (scaleX >= 1f) {
videoView.setScaleX(scaleX);
} else {
videoView.setScaleY(1f / scaleX);
}
}
});

//store the SurfaceTexture to set surface for MediaPlayer
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
FullScreenActivity.this.mSurface = surface;
}

Just manage overhang of the video out of FrameLayout
<FrameLayout
android:id="#+id/videoViewHolder"
android:layout_width="match_parent"
android:layout_height="200dp"
tools:visibility="visible">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center"/>
</FrameLayout>

Related

how to get width and height of videoview after video added

layout xml of videoview :
<RelativeLayout
android:id="#+id/videoEditorParent"
android:layout_width="match_parent"
android:layout_height="400dp">
<RelativeLayout
android:id="#+id/vidEditorWrapper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#color/colorAccent">
<VideoView
android:id="#+id/vidEditor"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</RelativeLayout>
when i get height and width of video view it gives me match_parent's width and height, but not aspect ratio width and height of video is playing in videoview(whatever width and height is covered in videoview by video).
here, my code :
viewWidth = vidEditor.getWidth();
viewHeight = vidEditor.getHeight();
ViewGroup.LayoutParams layoutParams = vidEditorWrapper.getLayoutParams();
dpWidthView = utilities.pxToDp(viewWidth);
dpHeightView = utilities.pxToDp(viewHeight);
dpWidthViewPerVal = (dpWidthView * 2) / 100;
layoutParams.width = viewWidth;
layoutParams.height = viewHeight;
vidEditorWrapper.setLayoutParams(layoutParams);
my screen shot :
i want width and height of black area that is video playing in videoview.
but getWidth() or getMeasuredWidth() and getHeight() or getMeasuredHeight() of videoview gives me match_parent width and height.
so, how can i get width and height of video area(only dark area that is visible to us in picture not full width) that is covered in videoview.
Try applying your code inside OnPreparedListener
For eg:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
viewWidth = vidEditor.getWidth();
viewHeight = vidEditor.getHeight();
ViewGroup.LayoutParams layoutParams =
vidEditorWrapper.getLayoutParams();
dpWidthView = utilities.pxToDp(viewWidth);
dpHeightView = utilities.pxToDp(viewHeight);
dpWidthViewPerVal = (dpWidthView * 2) / 100;
layoutParams.width = viewWidth;
layoutParams.height = viewHeight;
vidEditorWrapper.setLayoutParams(layoutParams);
}
});

CollapsingToolbarLayout image with zoom

I've been reading around all day without any success on this.
Basically want to be able to set an ImageView inside a android.support.design.widget.CollapsingToolbarLayout to change it's height depending on the onOffsetChanged change detected so that it will "zoom-out" when collapsed to fit the whole image width and "zoom-in" when expanded to do normal centerCrop behavior.
I tried setting the ImageView height in the onOffsetChanged but that causes other issues assuming due to the CollapsingToolbarLayout is also repositioning it.
Sample functionality I've seen in ParallaxListView project but wish to use the CollapsingToolbarLayout.
Anyone able to give sample code (if it is possible)?
Also seen this project but again similar limitation. Other projects as well.
You can try using android:scaleType="matrix"for the collapsing image's layout definition.
In the code,
store the initial ImageMatrix in a Matrix using matrix.set(imageView.getImageMatrix());
And depending upon the scroll of collapsing toolbar, you can use matrix.postScale() to scale the image and finally set it back to the ImageView using imageView.setImageMatrix(matrix). That can give you the zoom in / out effect.
I managed to do it in the end with the following code for anyone else out there that it may help. The code will fit to width when expanded and fit to height when collapsed. It can be changed to scale (zoom) further in if needed.
Not sure if optimal code is written, suggestions welcome. To measure the bitmap and the view and calculate the min/max scale I use the first call to onOffsetChanged which seems to work fine.
public class MyActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener {
private float collapsedScale;
private float expandedScale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(entry.label);
photoView = (ImageView) findViewById(R.id.photo_image);
AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
mAppBarLayout.addOnOffsetChangedListener(this);
}
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
int maxScroll = appBarLayout.getTotalScrollRange();
float scrollPercent = (float) Math.abs(verticalOffset) / (float) maxScroll;
if (collapsedScale == 0) {
Drawable photo = photoView.getDrawable();
int bitmapWidth = photo.getIntrinsicWidth();
int bitmapHeight = photo.getIntrinsicHeight();
collapsedScale = (float)photoView.getWidth()/(float)bitmapWidth;
expandedScale = (float)photoView.getHeight()/(float)bitmapHeight;
scalePhotoImage(photoView, expandedScale);
} else {
scalePhotoImage(photoView, collapsedScale + (expandedScale - collapsedScale) * (1f - scrollPercent));
}
}
private static void scalePhotoImage(ImageView photoView, float scale) {
Drawable photo = photoView.getDrawable();
int bitmapWidth = photo.getIntrinsicWidth();
int bitmapHeight = photo.getIntrinsicHeight();
float offsetX = (photoView.getWidth() - bitmapWidth) / 2F;
float offsetY = (photoView.getHeight() - bitmapHeight) / 2F;
float centerX = photoView.getWidth() / 2F;
float centerY = photoView.getHeight() / 2F;
Matrix imageMatrix = new Matrix();
imageMatrix.setScale(scale, scale, centerX, centerY);
imageMatrix.preTranslate(offsetX, offsetY);
photoView.setImageMatrix(imageMatrix);
}
}
My layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/menu_background_color"
tools:context="style.donkey.android.EntryDetailsActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:elevation="6dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
app:contentScrim="#android:color/transparent">
<ImageView
android:id="#+id/photo_image"
android:layout_width="match_parent"
android:layout_height="300dp"
android:src="#drawable/demo_photo"
android:fitsSystemWindows="true"
android:scaleType="matrix"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:theme = "#style/ToolBarStyle"
app:layout_collapseMode="pin">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<include layout="#layout/content_layout" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Issue with CoordinatorLayout and ImageView that adjusts width while scrolling

I'm attempting to put an ImageView in a CollapsingToolbarLayout in which it takes up the full screen on load and as you scroll the content, the 16x9 resolution image width resizes until the image takes up the full width of the screen. At that point, I'd like the image to parallax with a app:layout_collapseParallaxMultiplier of 0.5
Using this XML Layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/img_hero"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/lake"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.5"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="none"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_scrolling"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="#android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>
Accomplishes the following:
Which the following shows what the actual boundaries of the image are:
As I scroll, I would like more of the image width to show as the height of the image shrinks and results in the following:
Once I get to this point, this is where I would like the collapse parallax multiplier of 0.5 to take effect.
I've messed with many different scroll behaviors, tried all of the ImageView scrollTypes, to no avail. Does anybody know if this is possible and if so, can provide any pointers into what I'm either doing wrong or not doing.
Do I need to create my own custom CoordinatorLayout.Behavior to accomplish this?
You can achieve what you want by tracking vertical offset of AppBarLayout. It has beautiful method addOnOffsetChangedListener, so you can scale your image depending on offset of AppBarLayout.
So, there are three things that you have to do to get it working:
You need to place your image into drawable-nodpi folder, to prevent Android from scaling it for different screen sizes.
Change your ImageView's property scaleType to matrix - it's needed as we will change matrix of this ImageView by ourselves.
Implement addOnOffsetChangedListener for you AppBarLayout by next way:
final ImageView imageView = (ImageView) findViewById(R.id.img_hero);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
Matrix matrix = new Matrix(imageView.getImageMatrix());
//get image's width and height
final int dwidth = imageView.getDrawable().getIntrinsicWidth();
final int dheight = imageView.getDrawable().getIntrinsicHeight();
//get view's width and height
final int vwidth = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
int vheight = imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom();
float scale;
float dx = 0, dy = 0;
float parallaxMultiplier = ((CollapsingToolbarLayout.LayoutParams) imageView.getLayoutParams()).getParallaxMultiplier();
//maintain the image's aspect ratio depending on offset
if (dwidth * vheight > vwidth * dheight) {
vheight += (verticalOffset); //calculate view height depending on offset
scale = (float) vheight / (float) dheight; //calculate scale
dx = (vwidth - dwidth * scale) * 0.5f; //calculate x value of the center point of scaled drawable
dy = -verticalOffset * (1 - parallaxMultiplier); //calculate y value by compensating parallaxMultiplier
} else {
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * 0.5f;
}
int currentWidth = Math.round(scale * dwidth); //calculate current intrinsic width of the drawable
if (vwidth <= currentWidth) { //compare view width and drawable width to decide, should we scale more or not
matrix.setScale(scale, scale);
matrix.postTranslate(Math.round(dx), Math.round(dy));
imageView.setImageMatrix(matrix);
}
}
});
What I did here is just get ImageView's source code to determine bounds when it has centerCrop scale type and then just calculate the scale and translation of matrix depending on verticalOffset. If scale value is less than 1.0f then we've just reached the point where our view's aspect ratio is equal to the drawable's aspect ratio, and we don't need to scale more.
Note:
It would work as you wish, only with the image whose width > height, otherwise its behavior would be the same as centerCrop
It would work only if your parallaxMultiplier is in between 0 and 1.
How it looks for me:

Android VideoView crop_center

I have a RelativeLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:foregroundGravity="center"
android:gravity="center"
android:orientation="horizontal" >
<VideoView
android:id="#+id/videoViewPanel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_centerInParent="true"/>
</RelativeLayout>
And what I need is to show video fullscreen cropped. If I could compare to ImageView, I need to show it as crop_center.
How can I make VideoView not to auto-resize video to fit center, but crop center?
In Android's VideoView, here is a simple and easy way to achieve the same effect as ImageView.ScaleType.CENTER_CROP
xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="#dimen/dimen_0dp"
android:layout_height="#dimen/dimen_0dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
In JAVA:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
float screenRatio = videoView.getWidth() / (float)
videoView.getHeight();
float scaleX = videoRatio / screenRatio;
if (scaleX >= 1f) {
videoView.setScaleX(scaleX);
} else {
videoView.setScaleY(1f / scaleX);
}
}
});
In Kotlin:
videoView.setOnPreparedListener { mediaPlayer ->
val videoRatio = mediaPlayer.videoWidth / mediaPlayer.videoHeight.toFloat()
val screenRatio = videoView.width / videoView.height.toFloat()
val scaleX = videoRatio / screenRatio
if (scaleX >= 1f) {
videoView.scaleX = scaleX
} else {
videoView.scaleY = 1f / scaleX
}
}
And this worked for me. Hope this will help someone.
The solution is to use TextureView instead of VideoView(SurfaceView).
TextureView does not make any manipulations with the content to fit it ti the screen.
Here is the code sample for the solution:
//store the SurfaceTexture to set surface for MediaPlayer
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
FullScreenActivity.this.mSurface = surface;
}
....
Surface s = new Surface(mSurface);
mPlayer = mp;
mp.setSurface(s);
scaleVideo(mp);//<-- this function scales video to run cropped
....
private void scaleVideo(MediaPlayer mPlayer) {
LayoutParams videoParams = (LayoutParams) mTextureView
.getLayoutParams();
DisplayMetrics dm = new DisplayMetrics();
FullScreenActivity.this.getWindowManager().getDefaultDisplay()
.getMetrics(dm);
final int height = dm.heightPixels;
final int width = dm.widthPixels;
int videoHeight = mPlayer.getVideoHeight();
int videoWidth = mPlayer.getVideoWidth();
double hRatio = 1;
hRatio = (height * 1.0 / videoHeight) / (width * 1.0 / videoWidth);
videoParams.x = (int) (hRatio <= 1 ? 0 : Math.round((-(hRatio - 1) / 2)
* width));
videoParams.y = (int) (hRatio >= 1 ? 0 : Math
.round((((-1 / hRatio) + 1) / 2) * height));
videoParams.width = width - videoParams.x - videoParams.x;
videoParams.height = height - videoParams.y - videoParams.y;
Log.e(TAG, "x:" + videoParams.x + " y:" + videoParams.y);
mTextureView.setScaleX(1.00001f);//<-- this line enables smoothing of the picture in TextureView.
mTextureView.requestLayout();
mTextureView.invalidate();
}
I just put video inside ConstraintLayout with such parameters. This helped stretch video and achieve android:scaleType="centerCrop" effect.
<VideoView
android:id="#+id/video_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_gravity="center_horizontal"
android:layout_width="0dp"
android:layout_height="0dp" />
To crop center in fullscreen you can still use a VideoView. Set the VideoView width and height to match the parent inside a RelativeLayout and adjust it to be bigger than the screen and set his position.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rootLayout"
tools:context="com.example.Activity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_height="match_parent">
<VideoView
android:id="#+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_centerVertical="true" />
</RelativeLayout>
</RelativeLayout>
And then in onCreate:
RelativeLayout rootView=(RelativeLayout) findViewById(R.id.rootLayout);
Display display=getWindowManager().getDefaultDisplay();
Point size=new Point();
display.getSize(size);
FrameLayout.LayoutParams rootViewParams = (FrameLayout.LayoutParams) rootView.getLayoutParams();
int videoWidth=864;
int videoHeight=1280;
if ((float)videoWidth/(float)videoHeight<(float)size.x/(float)size.y) {
rootViewParams.width=size.x;
rootViewParams.height=videoHeight*size.x/videoWidth;
rootView.setX(0);
rootView.setY((rootViewParams.height-size.y)/2*-1);
} else {
rootViewParams.width=videoWidth*size.y/videoHeight;
rootViewParams.height=size.y;
rootView.setX((rootViewParams.width-size.x)/2*-1);
rootView.setY(0);
}
rootView.setLayoutParams(rootViewParams);
final VideoView mVideoView=(VideoView)findViewById(R.id.video_view);
mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash));
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mVideoView.start();
}
});
I have found a solution: The default behavior is just like fitCenter , so I compute the video ratio(width/height) and screen ratio, and then scale the VideoView to full screen. The result is just like centerCrop .

Position Video Inside a VideoView

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.
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 FrameLayout does. Here is the XML that fit my video to the screen, preserving the ratio and centering it:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg">
<!-- Video player -->
<VideoView
android:id="#+id/surface_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"/>
</FrameLayout>
In order to center the video in the RelativeLayout I added both layout_gravity="center" ad layout_centerInParent="true". It works on my Android 4.3 phone.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_centerInParent="true" />
</RelativeLayout>
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)
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(this);
fl.setLayoutParams(lp);
VideoView vv = new VideoView(this);
FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(lp);
lp2.gravity = Gravity.CENTER;
vv.setLayoutParams(lp2);
fl.addView(vv);
setContentView(fl);
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.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In onCreate:
Uri uri = //The uri of your video.
VideoView videoView = findViewById(R.id.videoView);
videoView.setVideoURI(uri);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
//Get your video's width and height
int videoWidth = mp.getVideoWidth();
int videoHeight = mp.getVideoHeight();
//Get VideoView's current width and height
int videoViewWidth = videoView.getWidth();
int videoViewHeight = videoView.getHeight();
float xScale = (float) videoViewWidth / videoWidth;
float yScale = (float) videoViewHeight / videoHeight;
//For Center Crop use the Math.max to calculate the scale
//float scale = Math.max(xScale, yScale);
//For Center Inside use the Math.min scale.
//I prefer Center Inside so I am using Math.min
float scale = Math.min(xScale, yScale);
float scaledWidth = scale * videoWidth;
float scaledHeight = scale * videoHeight;
//Set the new size for the VideoView based on the dimensions of the video
ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
layoutParams.width = (int)scaledWidth;
layoutParams.height = (int)scaledHeight;
videoView.setLayoutParams(layoutParams);
}
});
Hope it helps someone!
If you are looking for the same effect as ImageView.ScaleType.CENTER_CROP feature in VideoView then
Here is a simple and easy solution
See my XML and Kotlin version answer here:
https://stackoverflow.com/a/59069292/6255841
In JAVA:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
float screenRatio = videoView.getWidth() / (float)
videoView.getHeight();
float scaleX = videoRatio / screenRatio;
if (scaleX >= 1f) {
videoView.setScaleX(scaleX);
} else {
videoView.setScaleY(1f / scale);
}
}
});

Categories

Resources