最近的一个 Android 需要用到扫码功能, 用的是 Zxing 开源库. Zxing 的集成就不说了, 但是 Zxing 默认的是横屏扫码, 在实际生产中并不适用, 需要改为竖屏扫描.
转竖屏步骤:
1>. AndroidManifest.xml 中把 activity 标签 CaptureActivity 部分的 screenOrientation 改为 portrait.
android:screenOrientation="portrait"
2>. CameraManager 类中的 getFramingRectInPreview() 方法, 将 left, right, top, bottom 改变.
- // 竖屏
- 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;
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) 之前添加
- 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; // Here we are swapping, that's the difference to #11
- width = height;
- height = tmp;
- data = rotatedData;
此时, 竖屏扫描已经可以实现了, 但是扫描复杂的图码时, 分辨率低的已经分不清纹理了, 很难识别出来, 所以需要优化识别率.
识别率优化:
1>. CameraConfigurationUtils 类中的 findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) 方法, 将 double screenAspectRatio = screenResolution.x / (double) screenResolution.y 改为
- double screenAspectRatio;
- if (screenResolution.x> screenResolution.y) {
- screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;
- } else {
- screenAspectRatio = (double) screenResolution.y / (double) screenResolution.x;
- }
2>. 至此, 识别率已经很大程度上的提高了, 若在要提高识别率, 可通过修改 CameraManager 类中的 MAX_FRAME_WIDTH 和 MAX_FRAME_HEIGHT 来提高精度.
来源: https://www.cnblogs.com/fx-blog/p/9037937.html