缩放全屏视频以保持宽高比

时间:2017-02-19 19:14:30

标签: android android-mediaplayer surfaceview android-videoview

我正在处理需要以最干净的方式显示全屏视频的应用程序。一个众所周知的例子就是Snapchat。观看快照时,视频是全屏的,并保持其纵横比。

目前,我使用自定义VideoView设置为match_parent。自定义VideoView的代码如下:

public class CustomVideoView extends VideoView {

    private int leftAdjustment;
    private int topAdjustment;

    public CustomVideoView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int videoWidth = getMeasuredWidth();
        int videoHeight = getMeasuredHeight();

        int viewWidth = getDefaultSize(0, widthMeasureSpec);
        int viewHeight = getDefaultSize(0, heightMeasureSpec);

        if (videoWidth == viewWidth) {
            int newWidth = (int) ((float) videoWidth / videoHeight * viewHeight);
            setMeasuredDimension(newWidth, viewHeight);
            leftAdjustment = -(newWidth - viewWidth) / 2;
        } else {
            int newHeight = (int) ((float) videoHeight / videoWidth * viewWidth);
            setMeasuredDimension(viewWidth, newHeight);
            topAdjustment = -(newHeight - viewHeight) / 2;

        }
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l + leftAdjustment, t + topAdjustment, r + leftAdjustment, b + topAdjustment);
    }
}

虽然这实际上保持了视频的宽高比,但大部分视频都在屏幕外。

几个问题:

  1. Snapchat如何做到这一点?是因为每个视频都记录在应用程序中,他们已经知道宽高比了吗?
  2. 在保持宽高比的同时显示全屏视频的最佳方法是什么?

0 个答案:

没有答案