android zxing QrCode 库集成转竖屏适配问题
由于zxing 这个库使用比较广泛,所以大家也都遇到这个问题了,甚至最早可以追溯到十年前甚至更早,所以原创是谁已经无法找到,表明转载又需要填原文链接,就腆着脸标个原创了,不过的确不是我的原创,感谢前辈们!(不过说,zxing 这么大个库,这么多人使用,依然到今天都没有适配这个问题,也是令人感到费解啊,不过可能是大家都有解决办法,也就懒得去搞了)
第一:找到 CameraManager 中的
public synchronized Rect getFramingRectInPreview()
方法里的:
rect.left = rect.left * cameraResolution.x / screenResolution.x;rect.right = rect.right * cameraResolution.x / screenResolution.x;rect.top = rect.top * cameraResolution.y / screenResolution.y;rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
修改为:
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;
第二:找到 CameraConfigurationManager 中的
void setDesiredCameraParameters(OpenCamera camera, boolean safeMode)
方法,在 theCamera.setParameters(parameters); 方法之前,添加:
theCamera.setDisplayOrientation(90);
第三:找到 DecodeHandler 里的
private void 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 #11width = height;height = tmp;data = rotatedData;
第四:找到 CameraConfigurationUtils 里的
public static Point 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;}
最后,如果要提升扫描成功概率,可以修改 CameraManager 中的 MAX_FRAME_WIDTH 属性和MAX_FRAME_HEIGHT 属性;
再次感谢前辈们的贡献!