代码片段分享opengl es

解决 GLSurfaceView 预览camera时 内容拉伸变

2019-11-08  本文已影响0人  花艺荣

问题: 如题。
解决: 按照设定的camera预览size及GLSurfaceView的宽高来缩放GLSurfaceView

大体代码

 public static int[] fixPreviewFrameII(GLSurfaceView glView)
    {
        int viewWidth = glView.getMeasuredWidth() ,viewHeight =glView.getMeasuredHeight();
        if(viewWidth< viewHeight){
            int temp = viewWidth;
            viewWidth = viewHeight;
            viewHeight = temp;
        }
        if (viewWidth == 0 || viewHeight == 0)
        {
            return null;
        }
        float pWith = AppBase.getAppBaseInstance().mSettings.previewW;
        float pHeight = AppBase.getAppBaseInstance().mSettings.preViewH;

        float   scaleHei = 1;
        float   scaleWid = pWith*viewHeight/pHeight/viewWidth;

       /* glView.setScaleX(scaleHei);
        glView.setScaleY(scaleWid); */

       /* android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(320, 240);
        glView.setLayoutParams(params);*/
        int[] size = new int[2];
        size[0] = (int)(viewWidth*scaleWid);
        size[1] = viewHeight;
        return size;
    }

在自定义GLSurfaceView中

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int mScaledWidth = size[1], mScaledHeight=size[0];

        if (0 == mScaledWidth || 0 == mScaledHeight) {
            setMeasuredDimension(width, height);
        } else {

            setMeasuredDimension(mScaledWidth, mScaledHeight);

        }
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        Log.i(TAG, "onSurfaceChanged...");
        size = CameraUtils.fixPreviewFrameII(this);
        post(new Runnable() {
            @Override
            public void run() {
                requestLayout();
            }
        });
        GLES20.glViewport(0, 0, width, height);

    }
上一篇下一篇

猜你喜欢

热点阅读