1、自定义TextureView
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.TextureView;
/**
* 视频自动居中裁剪自定义TextureView
*/
public class TextureVideoView extends TextureView{
private float mVideoHeight;
private float mVideoWidth;
private ScaleType mScaleType;
public enum ScaleType {
CENTER_CROP, TOP, BOTTOM
}
public void setWH(float mVideoWidth,float mVideoHeight){
this.mVideoWidth=mVideoWidth;
this.mVideoHeight=mVideoHeight;
updateTextureViewSize();
}
public TextureVideoView(Context context) {
super(context);
initView();
}
public TextureVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public TextureVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
setScaleType(ScaleType.CENTER_CROP);
}
public void setScaleType(ScaleType scaleType) {
mScaleType = scaleType;
}
private void updateTextureViewSize() {
float sx = (float) getWidth() / mVideoWidth;
float sy = (float) getHeight() / mVideoHeight;
Matrix matrix = new Matrix();
float maxScale = Math.max(sx, sy);
//第1步:把视频区移动到View区,使两者中心点重合.
matrix.preTranslate((getWidth() - mVideoWidth) / 2, (getHeight() - mVideoHeight) / 2);
//第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
matrix.preScale(mVideoWidth / (float) getWidth(), mVideoHeight / (float) getHeight());
//第3步,等比例放大或缩小,直到视频区的一边超过View一边, 另一边与View的另一边相等. 因为超过的部分超出了View的范围,所以是不会显示的,相当于裁剪了.
matrix.postScale(maxScale, maxScale, getWidth() / 2, getHeight() / 2);//后两个参数坐标是以整个View的坐标系以参考的
setTransform(matrix);
}
}
二、设置mTextureVideoView.setScaleType(TextureVideoView.ScaleType.CENTER_CROP);属性
三、当获取到视频的宽高时mTextureVideoView.setWH()
注:Exo获取视频宽高方法:
player.setVideoListener(new SimpleExoPlayer.VideoListener() {
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
//视频宽和高
}
@Override
public void onRenderedFirstFrame() {
}
});
}