在zxing开发中camera除了用到上述接口外还有一些参数设置 Camera.Parameters,这里主要在CameraConfigurationManagerw完成的,由于google源码zxing是横屏的,他在获取屏幕的时候在竖屏的时候自动转换为横屏,代码如下:

if (width < height) {

             int temp = width;

              width = height;

              height = temp;

         }
boolean isCandidatePortrait = realWidth < realHeight;

int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth;

int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight;

所以在更改横竖屏的时候这段代码很重要,很多人都在DecodeHandler中添加

byte[] rotatedData = new byte[data.length];

    for (int y = 0; y < height; y++) {

        for (int x = 0; x < width; x++)

            rotatedData[x * height + height - y - 1] = data[x + y * width];

    }

    int tmp = width;

    width = height;

    height = tmp;

data = rotatedData;

这个就把获取到的横屏数据转为竖屏的,但这个有点繁琐,如果更改上述代码同时也要更改CameraManager中的

      rect.left = rect.left * cameraResolution.y / screenResolution.x;

      rect.right = rect.right * cameraResolution.y / screenResolution.x;

      rect.top = rect.top * cameraResolution.x / screenResolution.y;

      rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;

      framingRectInPreview = rect;

    }

这样才可以转换为竖屏,不过这样改动有一个很突出的问题,哪就是在竖屏的时候看到的二维码的高被拉伸了,这就是我说的之前google源码中把竖屏也强制转换为横屏留下的,最好的解决方案就是把CameraConfiguration中的获取窗口大小的代码 screenResolution = new Point(width,height);中的width与height调换,这样我们就获取竖屏的窗口,也可以保证横竖屏转换后看到的二维码看着不被拉伸,当然后面的代码都不用变,在setDesiredCameraParameters(Camera camera, boolean safeMode)中添加 camera.setDisplayOrientation(90);和把Manifest中CaptureActivity的设置android:screenOrientation=”landscape”即可,这样我们就完成了横竖屏的完美转换。

点此跳转原文