Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 以 Google ZXing 打造仿微信風格的二維碼掃描介面

編輯:Android 開發實例

微信帶起一波二維碼熱潮之後,商城、餐廳、包裝印刷品上幾乎處處可見。Android 端做二維碼掃描,主流選擇仍是 Google 的開源專案 ZXing,官方網站上可以取到原始碼與預先編譯好的 JAR。不過很多人第一次做出來的成品,功能跑得起來,介面卻實在難以入目。對一般使用者而言,UI 往往就是決定要不要繼續用下去的關鍵,所以這次我參照微信的掃描頁做了一輪改造,把改版後的介面與掃描邏輯一起整理出來:一方面方便日後自己直接複用,一方面也給還沒接觸過這個功能的人一個起點。

需要複製哪些檔案

整個方案可以拆成三個自訂套件與一個第三方 JAR。把 com.mining.app.zxing.camera、com.mining.app.zxing.decoding、com.mining.app.zxing.view 這三個套件整包搬進你的專案,再把對應的圖片與版面資源一起帶過去,最後記得掛上 zxing.jar。這裡我懶得改套件名稱,直接沿用原專案的命名。

com.example.qr_codescan 底下的 MipcaActivityCapture 是掃描頁的控制核心,負責處理相機生命週期、掃描成功後的提示音與震動等細節。你真正需要關注的只有一個方法:handleDecode(Result result, Bitmap barcode)。掃描完成時,系統會把解出的文字結果與碼圖本身當作參數傳進來,剩下的業務處理寫在這裡就好,其他流程不必更動。

一、handleDecode:結果回傳的出口

  1. /**   
  2.  * 處理掃描結果   
  3.  * @param result   
  4.  * @param barcode   
  5.  */    
  6. public void handleDecode(Result result, Bitmap barcode) {    
  7.     inactivityTimer.onActivity();    
  8.     playBeepSoundAndVibrate();    
  9.     String resultString = result.getText();    
  10.     if (resultString.equals("")) {    
  11.         Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();    
  12.     }else {    
  13.         Intent resultIntent = new Intent();    
  14.         Bundle bundle = new Bundle();    
  15.         bundle.putString("result", resultString);    
  16.         bundle.putParcelable("bitmap", barcode);    
  17.         resultIntent.putExtras(bundle);    
  18.         this.setResult(RESULT_OK, resultIntent);    
  19.     }    
  20.     MipcaActivityCapture.this.finish();    
  21. }    

二、掃描頁版面配置

版面採用 FrameLayout 外層包 RelativeLayout 的組合,把相機預覽、取景框覆層與標題列疊在一起。標題列我另外抽成獨立檔案,因為同一個專案裡其他頁面也在用它,重複利用比複製貼上乾淨。

  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"    
  3.     android:layout_width="fill_parent"    
  4.         android:layout_height="fill_parent" >    
  5.     
  6.     <RelativeLayout    
  7.         android:layout_width="fill_parent"    
  8.         android:layout_height="fill_parent" >    
  9.     
  10.         <SurfaceView    
  11.             android:id="@+id/preview_view"    
  12.             android:layout_width="fill_parent"    
  13.             android:layout_height="fill_parent"    
  14.             android:layout_gravity="center" />    
  15.     
  16.         <com.mining.app.zxing.view.ViewfinderView    
  17.             android:id="@+id/viewfinder_view"    
  18.             android:layout_width="wrap_content"    
  19.             android:layout_height="wrap_content" />    
  20.     
  21.         <include    
  22.             android:id="@+id/include1"    
  23.             android:layout_width="fill_parent"    
  24.             android:layout_height="wrap_content"    
  25.             android:layout_alignParentTop="true"    
  26.             layout="@layout/activity_title" />    
  27.     </RelativeLayout>    
  28.     
  29. </FrameLayout>   

標題列本體只有一個返回鍵與一個置中的標題文字,背景使用半透明的漸層素材,讓它疊在相機預覽上時不會顯得突兀:

  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"    
  3.     android:layout_width="fill_parent"    
  4.     android:layout_height="wrap_content"    
  5.     android:background="@drawable/mmtitle_bg_alpha" >    
  6.     
  7.     <Button    
  8.         android:id="@+id/button_back"    
  9.         android:layout_width="75.0dip"    
  10.         android:text="返回"    
  11.         android:background="@drawable/mm_title_back_btn"    
  12.         android:textColor="@android:color/white"    
  13.         android:layout_height="wrap_content"    
  14.         android:layout_centerVertical="true"    
  15.         android:layout_marginLeft="2dip" />    
  16.     
  17.     <TextView    
  18.         android:id="@+id/textview_title"    
  19.         android:layout_width="wrap_content"    
  20.         android:layout_height="wrap_content"    
  21.         android:layout_alignBaseline="@+id/button_back"    
  22.         android:layout_alignBottom="@+id/button_back"    
  23.         android:layout_centerHorizontal="true"    
  24.         android:gravity="center_vertical"    
  25.         android:text="二維碼掃描"    
  26.         android:textColor="@android:color/white"    
  27.         android:textSize="18sp" />    
  28.     
  29. </RelativeLayout>   

三、主頁面接收結果

Demo 的主頁面放了一顆按鈕、一個 ImageView 與一個 TextView。按鈕以 startActivityForResult 帶我們進入掃描頁,掃描成功後回到主頁面,把解出的字串塞進 TextView,順便也把拍到的碼圖顯示出來——這張圖你完全可以不要,我只是順手加上。

  1. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"    
  2.     xmlns:tools="https://schemas.android.com/tools"    
  3.     android:layout_width="match_parent"    
  4.     android:layout_height="match_parent"    
  5.     android:background="#ffe1e0de">    
  6.     
  7.     <Button    
  8.         android:id="@+id/button1"    
  9.         android:layout_width="fill_parent"    
  10.         android:layout_height="wrap_content"    
  11.         android:layout_alignParentTop="true"    
  12.         android:text="掃描二維碼" />    
  13.     
  14.     <TextView    
  15.         android:id="@+id/result"    
  16.         android:layout_width="fill_parent"    
  17.         android:layout_height="wrap_content"    
  18.         android:layout_below="@+id/button1"    
  19.         android:lines="2"    
  20.         android:gravity="center_horizontal"    
  21.         android:textColor="@android:color/black"    
  22.         android:textSize="16sp" />    
  23.     
  24.     <ImageView    
  25.         android:id="@+id/qrcode_bitmap"    
  26.         android:layout_width="fill_parent"    
  27.         android:layout_height="fill_parent"    
  28.         android:layout_alignParentLeft="true"    
  29.         android:layout_below="@+id/result"/>    
  30. </RelativeLayout>  
  1. package com.example.qr_codescan;    
  2.     
  3.     
  4. import android.app.Activity;    
  5. import android.content.Intent;    
  6. import android.graphics.Bitmap;    
  7. import android.os.Bundle;    
  8. import android.view.View;    
  9. import android.view.View.OnClickListener;    
  10. import android.widget.Button;    
  11. import android.widget.ImageView;    
  12. import android.widget.TextView;    
  13.     
  14. public class MainActivity extends Activity {    
  15.     private final static int SCANNIN_GREQUEST_CODE = 1;    
  16.     /**   
  17.      * 顯示掃描結果   
  18.      */    
  19.     private TextView mTextView ;    
  20.     /**   
  21.      * 顯示掃描拍的圖片   
  22.      */    
  23.     private ImageView mImageView;    
  24.         
  25.     
  26.     @Override    
  27.     protected void onCreate(Bundle savedInstanceState) {    
  28.         super.onCreate(savedInstanceState);    
  29.         setContentView(R.layout.activity_main);    
  30.             
  31.         mTextView = (TextView) findViewById(R.id.result);     
  32.         mImageView = (ImageView) findViewById(R.id.qrcode_bitmap);    
  33.             
  34.         //點擊按鈕跳轉到二維碼掃描界面,這裡用的是startActivityForResult跳轉     
  35.         //掃描完了之後調到該界面     
  36.         Button mButton = (Button) findViewById(R.id.button1);    
  37.         mButton.setOnClickListener(new OnClickListener() {    
  38.                  
  39.             @Override    
  40.             public void onClick(View v) {    
  41.                 Intent intent = new Intent();    
  42.                 intent.setClass(MainActivity.this, MipcaActivityCapture.class);    
  43.                 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
  44.                 startActivityForResult(intent, SCANNIN_GREQUEST_CODE);    
  45.             }    
  46.         });    
  47.     }    
  48.         
  49.         
  50.     @Override    
  51.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
  52.         super.onActivityResult(requestCode, resultCode, data);    
  53.         switch (requestCode) {    
  54.         case SCANNIN_GREQUEST_CODE:    
  55.             if(resultCode == RESULT_OK){    
  56.                 Bundle bundle = data.getExtras();    
  57.                 //顯示掃描到的內容     
  58.                 mTextView.setText(bundle.getString("result"));    
  59.                 //顯示     
  60.                 mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));    
  61.                }    
  62.                break;    
  63.             }    
  64.     }        
  65.     
  66. }    

四、關鍵:改寫 ViewfinderView

上面那些都還算直覺,但要做出微信那種取景框質感,一定要動 com.mining.app.zxing.view 底下的 ViewfinderView。微信用的是切圖,我這裡改成純 Canvas 繪製:四個綠色直角、中間一條上下移動的掃描線、框外半透明遮罩,以及框下方的提示文字。註解寫得比較細,直接看程式碼即可。若要調整掃描框尺寸,請改 CameraManager。

  1. package com.mining.app.zxing.view;    
  2.     
  3. import java.util.Collection;    
  4. import java.util.HashSet;    
  5.     
  6. import android.content.Context;    
  7. import android.content.res.Resources;    
  8.     
  9. import android.graphics.Bitmap;    
  10. import android.graphics.Canvas;    
  11.     
  12. import android.graphics.Color;    
  13. import android.graphics.Paint;    
  14.     
  15. import android.graphics.Rect;    
  16. import android.graphics.Typeface;    
  17.     
  18. import android.util.AttributeSet;    
  19. import android.view.View;    
  20.     
  21. import com.example.qr_codescan.R;    
  22. import com.google.zxing.ResultPoint;    
  23.     
  24. import com.mining.app.zxing.camera.CameraManager;    
  25.  
  26. /**   
  27.  * 此視圖覆蓋在相機預覽之上,負責繪製取景框、框外半透明遮罩、掃描線動畫與定位點   
  28.  */    
  29. public final class ViewfinderView extends View {    
  30.     private static final String TAG ="log";    
  31.     /**   
  32.      * 刷新界面的時間   
  33.      */    
  34.     private static final long ANIMATION_DELAY = 10L;    
  35.     private static final int OPAQUE = 0xFF;    
  36.     
  37.     /**   
  38.      * 四個綠色邊角對應的長度   
  39.      */    
  40.     private int ScreenRate;    
  41.     
  42.     /**   
  43.      * 四個綠色邊角對應的寬度   
  44.      */    
  45.     private static final int CORNER_WIDTH = 10;    
  46.     
  47.     /**   
  48.      * 掃描框中的中間線的寬度   
  49.      */    
  50.     private static final int MIDDLE_LINE_WIDTH = 6;    
  51.     
  52.     /**   
  53.      * 掃描框中的中間線的與掃描框左右的間隙   
  54.      */    
  55.     private static final int MIDDLE_LINE_PADDING = 5;    
  56.     
  57.     /**   
  58.      * 中間那條線每次刷新移動的距離   
  59.      */    
  60.     private static final int SPEEN_DISTANCE = 5;    
  61.     
  62.     /**   
  63.      * 手機的屏幕密度   
  64.      */    
  65.     private static float density;    
  66.     
  67.     /**   
  68.      * 字體大小   
  69.      */    
  70.     private static final int TEXT_SIZE = 16;    
  71.     
  72.     /**   
  73.      * 字體距離掃描框下面的距離   
  74.      */    
  75.     private static final int TEXT_PADDING_TOP = 30;    
  76.     
  77.     /**   
  78.      * 畫筆對象的引用   
  79.      */    
  80.     private Paint paint;    
  81.     
  82.     /**   
  83.      * 中間滑動線的最頂端位置   
  84.      */    
  85.     private int slideTop;    
  86.     
  87.     /**   
  88.      * 中間滑動線的最底端位置   
  89.      */    
  90.     private int slideBottom;    
  91.     
  92.     private Bitmap resultBitmap;    
  93.     private final int maskColor;    
  94.     private final int resultColor;    
  95.     
  96.     private final int resultPointColor;    
  97.     private Collection<ResultPoint> possibleResultPoints;    
  98.     private Collection<ResultPoint> lastPossibleResultPoints;    
  99.     
  100.     boolean isFirst;    
  101.     
  102.     public ViewfinderView(Context context, AttributeSet attrs) {    
  103.         super(context, attrs);    
  104.             
  105.         density = context.getResources().getDisplayMetrics().density;    
  106.         //將像素轉換成dp     
  107.         ScreenRate = (int)(20 * density);    
  108.     
  109.         paint = new Paint();    
  110.         Resources resources = getResources();    
  111.         maskColor = resources.getColor(R.color.viewfinder_mask);    
  112.         resultColor = resources.getColor(R.color.result_view);    
  113.     
  114.         resultPointColor = resources.getColor(R.color.possible_result_points);    
  115.         possibleResultPoints = new HashSet<ResultPoint>(5);    
  116.     }    
  117.     
  118.     @Override    
  119.     public void onDraw(Canvas canvas) {    
  120.         //中間的掃描框,你要修改掃描框的大小,去CameraManager裡面修改     
  121.         Rect frame = CameraManager.get().getFramingRect();    
  122.         if (frame == null) {    
  123.             return;    
  124.         }    
  125.             
  126.         //初始化中間線滑動的最上邊和最下邊     
  127.         if(!isFirst){    
  128.             isFirst = true;    
  129.             slideTop = frame.top;    
  130.             slideBottom = frame.bottom;    
  131.         }    
  132.             
  133.         //獲取屏幕的寬和高     
  134.         int width = canvas.getWidth();    
  135.         int height = canvas.getHeight();    
  136.     
  137.         paint.setColor(resultBitmap != null ? resultColor : maskColor);    
  138.             
  139.         //畫出掃描框外面的陰影部分,共四個部分     
  140.         canvas.drawRect(0, 0, width, frame.top, paint);    
  141.         canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);    
  142.         canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,    
  143.                 paint);    
  144.         canvas.drawRect(0, frame.bottom + 1, width, height, paint);    
  145.     
  146.             
  147.     
  148.         if (resultBitmap != null) {    
  149.             paint.setAlpha(OPAQUE);    
  150.             canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);    
  151.         } else {    
  152.     
  153.             //畫掃描框邊上的角,總共8個部分     
  154.             paint.setColor(Color.GREEN);    
  155.             canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,    
  156.                     frame.top + CORNER_WIDTH, paint);    
  157.             canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top    
  158.                     + ScreenRate, paint);    
  159.             canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,    
  160.                     frame.top + CORNER_WIDTH, paint);    
  161.             canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top    
  162.                     + ScreenRate, paint);    
  163.             canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left    
  164.                     + ScreenRate, frame.bottom, paint);    
  165.             canvas.drawRect(frame.left, frame.bottom - ScreenRate,    
  166.                     frame.left + CORNER_WIDTH, frame.bottom, paint);    
  167.             canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,    
  168.                     frame.right, frame.bottom, paint);    
  169.             canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,    
  170.                     frame.right, frame.bottom, paint);    
  171.     
  172.             //繪制中間的線,每次刷新界面,中間的線往下移動SPEEN_DISTANCE     
  173.             slideTop += SPEEN_DISTANCE;    
  174.             if(slideTop >= frame.bottom){    
  175.                 slideTop = frame.top;    
  176.             }    
  177.             canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);    
  178.     
  179.             //畫掃描框下面的字     
  180.             paint.setColor(Color.WHITE);    
  181.             paint.setTextSize(TEXT_SIZE * density);    
  182.             paint.setAlpha(0x40);    
  183.             paint.setTypeface(Typeface.create("System", Typeface.BOLD));    
  184.             canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);    
  185.     
  186.             Collection<ResultPoint> currentPossible = possibleResultPoints;    
  187.             Collection<ResultPoint> currentLast = lastPossibleResultPoints;    
  188.             if (currentPossible.isEmpty()) {    
  189.                 lastPossibleResultPoints = null;    
  190.             } else {    
  191.                 possibleResultPoints = new HashSet<ResultPoint>(5);    
  192.                 lastPossibleResultPoints = currentPossible;    
  193.                 paint.setAlpha(OPAQUE);    
  194.                 paint.setColor(resultPointColor);    
  195.                 for (ResultPoint point : currentPossible) {    
  196.                     canvas.drawCircle(frame.left + point.getX(), frame.top    
  197.                             + point.getY(), 6.0f, paint);    
  198.                 }    
  199.             }    
  200.             if (currentLast != null) {    
  201.                 paint.setAlpha(OPAQUE / 2);    
  202.                 paint.setColor(resultPointColor);    
  203.                 for (ResultPoint point : currentLast) {    
  204.                     canvas.drawCircle(frame.left + point.getX(), frame.top    
  205.                             + point.getY(), 3.0f, paint);    
  206.                 }    
  207.             }    
  208.     
  209.         //只刷新掃描框的內容,其他地方不刷新     
  210.         postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,    
  211.                     frame.right, frame.bottom);    
  212.             
  213.     }    
  214.     
  215.     public void drawViewfinder() {    
  216.         resultBitmap = null;    
  217.         invalidate();    
  218.     }    
  219.     
  220.     public void drawResultBitmap(Bitmap barcode) {    
  221.         resultBitmap = barcode;    
  222.         invalidate();    
  223.     }    
  224.     
  225.     public void addPossibleResultPoint(ResultPoint point) {    
  226.         possibleResultPoints.add(point);    
  227.     }    
  228.     
  229. }    

兩個可以再打磨的小地方

中間那條掃描線我是用 drawRect 畫的。若你想要更接近微信的質感,把畫矩形的部分換成貼圖即可:

  1. canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);

改寫成:

  1. Rect lineRect = new Rect();    
  2.             lineRect.left = frame.left;    
  3.             lineRect.right = frame.right;    
  4.             lineRect.top = slideTop;    
  5.             lineRect.bottom = slideTop + 18;    
  6.             canvas.drawBitmap(((BitmapDrawable)(getResources().getDrawable(R.drawable.qrcode_scan_line))).getBitmap(), null, lineRect, paint);    

那條掃描線的素材要自己從微信 APK 裡撈:把 .apk 副檔名改成 .zip 解壓就能找到圖片資源。

另一處是框下方提示文字。原本的寫法是從框的左上角開始畫,文字長短不同時會偏一邊,改成先量寬再置中比較穩妥(字太長需要換行的情況這裡沒有處理,可以自行補上):

  1. paint.setColor(Color.WHITE);      
  2. paint.setTextSize(TEXT_SIZE * density);      
  3. paint.setAlpha(0x40);      
  4. paint.setTypeface(Typeface.DEFAULT_BOLD);      
  5. String text = getResources().getString(R.string.scan_text);      
  6. float textWidth = paint.measureText(text);      
  7.     
  8. canvas.drawText(text, (width - textWidth)/2, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint)   

跑起來之後,取景框中間那條綠線會持續上下移動,視覺效果與微信相當接近。最後別忘了在 Manifest 裡補上相機與網路相關的權限,否則程式會在初始化階段就失敗。

原文轉自:https://blog.csdn.net/xiaanming/article/details/10163203

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