Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

二維碼掃描實戰:支援橫屏與豎屏、解決拉伸並美化掃描框

編輯:關於 Android 程式設計

以下做法基於 zxing 源碼簡化而來,原本只支援橫屏。要改為支援豎屏其實也不難,可依下列步驟調整。

支援豎屏的五個步驟

Step 1:在 DecodeHandler.java 的 decode(byte[] data, int width, int height) 中,於 buildLuminanceSource(..) 之前旋轉資料:

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;
width = height;
height = tmp;
PlanarYUVLuminanceSource source =
        activity.getCameraManager().buildLuminanceSource(rotatedData, width, height);

Step 2:修改 CameraManager.java 的 getFramingRectInPreview():

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;

Step 3:在 CameraConfigurationManager.java 的 initFromCameraParameters(...) 中,移除針對橫屏模式的檢查:

// 移除以下這段
if (width < height) {
    Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect");
    int temp = width;
    width = height;
    height = temp;
}

Step 4:在 setDesiredCameraParameters(...) 中加入旋轉:

camera.setDisplayOrientation(90);

Step 5:別忘了在 manifest 中把 Activity 的 orientation 設為 portrait。

解決豎屏後的拉伸問題

完成上述設定後畫面可能出現拉伸,解法是修改 CameraConfigurationManager.java:在 Log.d(TAG, "Screen resolution: " + screenResolution); 之後加入:

Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
// preview size 通常是 480*320 之類,需對調
if (screenResolution.x < screenResolution.y) {
    screenResolutionForCamera.x = screenResolution.y;
    screenResolutionForCamera.y = screenResolution.x;
}

再把 cameraResolution = getCameraResolution(parameters, screenResolution); 改為:

cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);

如此一來,豎屏下的預覽畫面就不會被拉伸變形。若想進一步美化掃描框(例如加上框線、動畫或自訂外觀),可參考社群上分享的取景框自訂範例進行調整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved