ijkMediaPlayer+ TextureView 等比全屏播放视频(避免拉伸)

TextureView默认以fitxy的方式加载surface数据,如果需要等比全屏播放视频,避免拉伸,可以采用Matrix对TextureView进行变换

废话不多说,直接上代码

public class BaseIjkPlayer implements TextureView.SurfaceTextureListener{

    //视频缩放,调整比例
    private void resolveStretching(float textureViewWidth,float textureViewHeight){
        if(textureView==null){
            return;
        }
        if(ijkMediaPlayer==null){
            return;
        }
        try {
            float videoWidth = ijkMediaPlayer.getVideoWidth(); //宽
            float videoHeight = ijkMediaPlayer.getVideoHeight(); //高
            if(textureViewWidth==0||textureViewHeight==0||videoWidth==0||videoHeight==0){
                return;
            }
            Matrix matrix = getMatrix(textureViewWidth, textureViewHeight, videoWidth, videoHeight);
            textureView.setTransform(matrix);
            textureView.postInvalidate();
        }catch (Exception e){
            Log.d(TAG, "resolveStretching: error"+e);
        }
    }
    
	//获取Matrix    
	private @NonNull Matrix getMatrix(float textureViewWidth,float textureViewHeight,float videoWidth,float videoHeight) {
        float sx = textureViewWidth / videoWidth;
        float sy = textureViewHeight/ videoHeight;
        Matrix matrix = new Matrix();
        //第1步:把视频区移动到View区,使两者中心点重合.
        matrix.preTranslate((textureViewWidth - videoWidth) / 2, (textureViewHeight - videoHeight) / 2);
        //第2步:因为默认视频是fitXY的形式显示的,所以首先要缩放还原回来.
        matrix.preScale(videoWidth / textureViewWidth, videoHeight / textureViewHeight);
        //第3步,等比例放大或缩小,直到视频区的一边和View一边相等.如果另一边和view的一边不相等,则留下空隙
        if (sx >= sy){
            matrix.postScale(sy, sy, textureViewWidth / 2, textureViewHeight / 2);
        }else{
            matrix.postScale(sx, sx, textureViewWidth / 2, textureViewHeight / 2);
        }
        return matrix;
    }
}

在onSurfaceTextureAvailable才能拿到textureViewWidth和textureViewHeight的真实长度

public class BaseIjkPlayer implements TextureView.SurfaceTextureListener{
    
 	@Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture sur, int width, int height) {
        this.surface = new Surface(sur);
        ijkMediaPlayer.setSurface(surface);
        resolveStretching(width,height);
    }
    //省略其他的SurfaceTextureListener的实现...
}

别忘了添加监听

public class BaseIjkPlayer implements TextureView.SurfaceTextureListener{
    public IjkMediaPlayer ijkMediaPlayer;
    //初始化
	private void init() {
	    ijkMediaPlayer = new IjkMediaPlayer();
	    //...省略一些配置
   		textureView.setSurfaceTextureListener(this);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值