Android開源二維碼識別項目zxing橫屏改為豎屏識別解決方案,androidzxing
在網上找了很多方法,但最後都有問題,自己調試了好幾個小時,最後終於完美解決了豎屏識別。
首先你需要有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中修改成自己喜歡的樣式。