我正在寻找类似于ImageView.ScaleType中的CENTER_CROP的东西。
将图像等比缩放(保持图像的长宽比),使图像的宽度和高度都大于或等于视图相应的尺寸(减去内边距)。然后在视图中心放置该图像。从XML中,使用这种语法:android:scaleType="centerCrop"
但用于VideoView。是否存在类似的东西?
我正在寻找类似于ImageView.ScaleType中的CENTER_CROP的东西。
将图像等比缩放(保持图像的长宽比),使图像的宽度和高度都大于或等于视图相应的尺寸(减去内边距)。然后在视图中心放置该图像。从XML中,使用这种语法:android:scaleType="centerCrop"
但用于VideoView。是否存在类似的东西?
只有使用TextureView才能达到这个效果(surfaceView也不行)。这是一个带有居中裁剪功能的lib,可在TextureView中播放视频。很遗憾,TextureView只能在14及以上的api级别中使用。
https://github.com/dmytrodanylyk/android-video-crop
另一种可能性是将VideoView放大到合适大小,但我还没有尝试过。
如果您使用的是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>
那么
在 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
}
}
查看我的 Java 版本答案,请点击此处:https://dev59.com/6W445IYBdhLWcg3w7urD#59069357
对我来说,这个方法有效。
Nabin的回答对我有用。
这是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);
}
}
});
//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;
}
仅管理视频超出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>