Android视频缩放

2018-08-30  本文已影响33人  yunhen

private WeakReference<TextureView> weak ;

在start()之前调用下面的方法

//重新计算video的显示位置,让其全部显示并据中
    public void updateSizeCenter(){
        int mVideoWidth = mMediaPlayer.getVideoWidth();
        int  mVideoHeight = mMediaPlayer.getVideoHeight();
        float sx = (float) weak.get().getWidth() / (float) mVideoWidth;
        float sy = (float) weak.get().getHeight() / (float) mVideoHeight;

        Matrix matrix = new Matrix();

        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((weak.get().getWidth() - mVideoWidth) / 2, (weak.get().getHeight() - mVideoHeight) / 2);

        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(mVideoWidth / (float) weak.get().getWidth(), mVideoHeight / (float) weak.get().getHeight());

        //第3步,等比例放大或缩小,直到视频区的一边和View一边相等.如果另一边和view的一边不相等,则留下空隙
        if (sx >= sy){
            matrix.postScale(sy, sy, weak.get().getWidth() / 2, weak.get().getHeight() / 2);
        }else{
            matrix.postScale(sx, sx, weak.get().getWidth() / 2, weak.get().getHeight() / 2);
        }

        weak.get().setTransform(matrix);
        weak.get().postInvalidate();
    }
    //重新计算video的显示位置,裁剪后全屏显示
    public void updateSizeCenterCrop(){
        int mVideoWidth = mMediaPlayer.getVideoWidth();
        int  mVideoHeight = mMediaPlayer.getVideoHeight();
        float sx = (float) weak.get().getWidth() / (float) mVideoWidth;
        float sy = (float) weak.get().getHeight() / (float) mVideoHeight;

        Matrix matrix = new Matrix();
        float maxScale = Math.max(sx, sy);

        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((weak.get().getWidth() - mVideoWidth) / 2, (weak.get().getHeight() - mVideoHeight) / 2);

        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(mVideoWidth / (float)weak.get(). getWidth(), mVideoHeight / (float) weak.get().getHeight());

        //第3步,等比例放大或缩小,直到视频区的一边超过View一边, 另一边与View的另一边相等. 因为超过的部分超出了View的范围,所以是不会显示的,相当于裁剪了.
        matrix.postScale(maxScale, maxScale, weak.get().getWidth() / 2, weak.get().getHeight() / 2);//后两个参数坐标是以整个View的坐标系以参考的

        weak.get().setTransform(matrix);
        weak.get().postInvalidate();
    }
上一篇 下一篇

猜你喜欢

热点阅读