最近的一个Android需要用到扫码功能,用的是Zxing开源库。Zxing的集成就不说了,但是Zxing默认的是横屏扫码,在实际生产中并不适用,需要改为竖屏扫描。
转竖屏步骤:
1>. AndroidManifest.xml中把activity标签CaptureActivity部分的screenOrientation改为portrait。
android:screenOrientation="portrait"
2>. CameraManager类中的getFramingRectInPreview()方法,将left, right, top, bottom改变。
1 //竖屏2 rect.left = rect.left * cameraResolution.y / screenResolution.x;3 rect.right = rect.right * cameraResolution.y / screenResolution.x;4 rect.top = rect.top * cameraResolution.x / screenResolution.y;5 rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
3>. CameraConfigurationManager类中的setDesiredCameraParameters(OpenCamera camera, boolean safeMode)方法,在setParameters之前添加
theCamera.setDisplayOrientation(90);
4>. DecodeHandler类中的decode(byte[] data, int width, int height)方法,在PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height)之前添加
1 byte[] rotatedData = new byte[data.length];2 for (int y = 0; y < height; y++) {3 for (int x = 0; x < width; x++)4 rotatedData[x * height + height - y - 1] = data[x + y * width];5 }6 int tmp = width; // Here we are swapping, that's the difference to #117 width = height;8 height = tmp;9 data = rotatedData;
此时,竖屏扫描已经可以实现了,但是扫描复杂的图码时,分辨率低的已经分不清纹理了,很难识别出来,所以需要优化识别率。
识别率优化:
1>. CameraConfigurationUtils类中的findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution)方法,将double screenAspectRatio = screenResolution.x / (double) screenResolution.y改为
1 double screenAspectRatio;2 if (screenResolution.x > screenResolution.y) {3 screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;4 } else {5 screenAspectRatio = (double) screenResolution.y / (double) screenResolution.x;6 }
2>. 至此,识别率已经很大程度上的提高了,若在要提高识别率,可通过修改CameraManager类中的MAX_FRAME_WIDTH和MAX_FRAME_HEIGHT来提高精度。