在網上找了很多方法,但最后都有問題,自己調試了好幾個小時,最后終於完美解決了豎屏識別。
首先你需要有zxing項目的簡化版代碼,在這里。
使用簡化版可以免去許多不必要的代碼,方便學習研究,更好定位核心功能。
如果你調試成功后,就可以着手修改將其變為豎屏識別了。
第1步:
在AndroidManifest中將CaptureActivity的screenOrientation屬性做如下修改:
android:screenOrientation="portrait"
第2步:
我們要把攝像頭預覽景調為豎向
CameraConfigurationManager類中的setDesiredCameraParameters()方法中添加如下代碼:
// 使攝像頭旋轉90度 setDisplayOrientation(camera, 90);
然后在CameraConfigurationManager類的最后添加setDisplayOrientation()方法:

/*改變照相機成像的方向的方法*/ protected void setDisplayOrientation(Camera camera, int angle) { Method downPolymorphic = null; try { downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class }); if (downPolymorphic != null) downPolymorphic.invoke(camera, new Object[]{angle}); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
最后在CameraConfigurationManager中的initFromCameraParameters()方法的Log.d(TAG, "Screen resolution: " + screenResolution);句后面添加如下代碼,這段代碼是為了解決攝像頭豎過來后圖像拉伸的問題:

//為豎屏添加 Point screenResolutionForCamera = new Point(); screenResolutionForCamera.x = screenResolution.x; screenResolutionForCamera.y = screenResolution.y; if (screenResolution.x < screenResolution.y) { screenResolutionForCamera.x = screenResolution.y; screenResolutionForCamera.y = screenResolution.x; } // 下句第二參數要根據豎屏修改 cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
第3步:
CameranManager類中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;
第4步:
PlanarYUVLuminanceSource類中的getRow()方法為識別條形碼部分,
getMatrix()方法為識別二維碼部分
renderCroppedGreyscaleBitmap()方法為生成獲取的碼圖部分
將getRow()中的:
int offset = (y + top) * dataWidth + left;
getMatrix()中的:
int inputOffset = top * dataWidth + left;
inputOffset += dataWidth;
renderCroppedGreyscaleBitmap()中的:
int inputOffset = top * dataWidth + left;
inputOffset += dataWidth;
這些語句中dataWidth全部替換為dataHeight
同時將PlanarYUVLuminanceSource構造方法中:
if (left + width > dataWidth || top + height > dataHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); }
dataWidth與dateHeight中互換位置即可。
此時,你的程序豎屏識別碼圖應該沒有任何問題了。至於取景框的樣式,大家可以在自定義的ViewfinderView中修改成自己喜歡的樣式。