EXOPlayer居中播放,類似ImageView的CENTER_CROP

Main-zy發表於2017-09-28

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() {

            }
        });

    }



相關文章