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

基於 Google ZXing 實現二維碼掃描,並仿微信掃描動效

編輯:關於 Android 程式設計

說起二維碼,很多人的記憶都始於微信。當年微信上線掃一掃,拿一張圖掃一下就能加好友,確實讓人覺得新鮮。那時候我對二維碼的認知還很模糊,後來項目裡要加掃描功能,上網一查,發現相關教程不少,就跟著做了一遍,功能很快跑通了,當時還挺得意。

隨著二維碼鋪開到商城、餐廳、收銀台各個角落,這個能力幾乎成了 App 的標配。實現方案上,我們用的還是 Google 的開源庫 ZXing,源碼和 jar 都可以從 https://code.google.com/p/zxing/ 獲取。

不過我最初那版只實現了「能掃」,UI 實在難以入目。一款應用能不能被接受,界面佔的權重並不比功能低,所以後面又照著微信的掃描頁做了一輪改造。雖然離微信的精緻度還有距離,但整體觀感已經能看了。下面把改進 UI 的思路和掃描代碼一起分享出來,一是自己以後遇到同樣需求可以直接複用,二是給還沒做過這個功能的朋友一個參考。

先看一眼項目結構:

  • 想把這個功能搬到自己項目裡,直接把 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) 方法——掃描完成後,結果字符串和截到的二維碼位圖會作為參數傳進來,你的業務處理寫在這裡就好,其他地方基本不用動。
 /** * 處理掃描結果 * @param result * @param barcode */ public void handleDecode(Result result, Bitmap barcode) { inactivityTimer.onActivity(); playBeepSoundAndVibrate(); String resultString = result.getText(); if (resultString.equals("")) { Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show(); }else { Intent resultIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("result", resultString); bundle.putParcelable("bitmap", barcode); resultIntent.putExtras(bundle); this.setResult(RESULT_OK, resultIntent); } MipcaActivityCapture.this.finish(); } 
  • 掃描界面的布局我做了改寫,主要用 FrameLayout 套 RelativeLayout,裡面的裝飾圖片是從微信裡扒出來的——公司沒配美工,程序員只能自己動手,這大概是很多人的日常。

布局代碼如下:

 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <SurfaceView android:id="@+id/preview_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" /> <com.mining.app.zxing.view.ViewfinderView android:id="@+id/viewfinder_view" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <include android:id="@+id/include1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" layout="@layout/activity_title" /> </RelativeLayout> </FrameLayout> 
  • 頂部欄我單獨抽成了一個布局再 include 進來,因為 activity_title 在項目裡還有其他 Activity 在用,直接複用更省事。
 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/mmtitle_bg_alpha" > <Button android:id="@+id/button_back" android:layout_width="75.0dip" android:text="返回" android:background="@drawable/mm_title_back_btn" android:textColor="@android:color/white" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="2dip" /> <TextView android:id="@+id/textview_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button_back" android:layout_alignBottom="@+id/button_back" android:layout_centerHorizontal="true" android:gravity="center_vertical" android:text="二維碼掃描" android:textColor="@android:color/white" android:textSize="18sp" /> </RelativeLayout> 

demo 裡有個 MainActivity,包含一個 Button、一個 ImageView 和一個 TextView。點 Button 進入掃描頁,掃描成功後返回主界面,把結果顯示到 TextView,把截到的圖片顯示到 ImageView。如果你不需要展示圖片,那部分直接去掉即可。

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffe1e0de" > <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="掃描二維碼" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:lines="2" android:gravity="center_horizontal" android:textColor="@android:color/black" android:textSize="16sp" /> <ImageView android:id="@+id/qrcode_bitmap" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_below="@+id/result"/> </RelativeLayout> 
  • MainActivity 的代碼如下,邏輯就是上面描述的那一套。
 package com.example.qr_codescan; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { private final static int SCANNIN_GREQUEST_CODE = 1; /** * 顯示掃描結果 */ private TextView mTextView ; /** * 顯示掃描拍的圖片 */ private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.result); mImageView = (ImageView) findViewById(R.id.qrcode_bitmap); //點擊按鈕跳轉到二維碼掃描界面,這裡用的是startActivityForResult跳轉 //掃描完了之後調到該界面 Button mButton = (Button) findViewById(R.id.button1); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(MainActivity.this, MipcaActivityCapture.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivityForResult(intent, SCANNIN_GREQUEST_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SCANNIN_GREQUEST_CODE: if(resultCode == RESULT_OK){ Bundle bundle = data.getExtras(); //顯示掃描到的內容 mTextView.setText(bundle.getString("result")); //顯示 mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap")); } break; } } }
  • 到這裡功能已經完整,但還做不出微信那種帶取景框的效果。要實現它,必須重寫 com.mining.app.zxing.view 下的 ViewfinderView。微信用的是切圖,我這裡直接用代碼畫,注釋寫得比較細,就不逐行解釋了。如果想改掃描框大小,去 CameraManager 類裡調整。
 /* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mining.app.zxing.view; import java.util.Collection; import java.util.HashSet; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.View; import com.example.qr_codescan.R; import com.google.zxing.ResultPoint; import com.mining.app.zxing.camera.CameraManager; /** * This view is overlaid on top of the camera preview. It adds the viewfinder * rectangle and partial transparency outside it, as well as the laser scanner * animation and result points. * */ public final class ViewfinderView extends View { private static final String TAG = "log"; /** * 刷新界面的時間 */ private static final long ANIMATION_DELAY = 10L; private static final int OPAQUE = 0xFF; /** * 四個綠色邊角對應的長度 */ private int ScreenRate; /** * 四個綠色邊角對應的寬度 */ private static final int CORNER_WIDTH = 10; /** * 掃描框中的中間線的寬度 */ private static final int MIDDLE_LINE_WIDTH = 6; /** * 掃描框中的中間線的與掃描框左右的間隙 */ private static final int MIDDLE_LINE_PADDING = 5; /** * 中間那條線每次刷新移動的距離 */ private static final int SPEEN_DISTANCE = 5; /** * 手機的屏幕密度 */ private static float density; /** * 字體大小 */ private static final int TEXT_SIZE = 16; /** * 字體距離掃描框下面的距離 */ private static final int TEXT_PADDING_TOP = 30; /** * 畫筆對象的引用 */ private Paint paint; /** * 中間滑動線的最頂端位置 */ private int slideTop; /** * 中間滑動線的最底端位置 */ private int slideBottom; private Bitmap resultBitmap; private final int maskColor; private final int resultColor; private final int resultPointColor; private Collection<ResultPoint> possibleResultPoints; private Collection<ResultPoint> lastPossibleResultPoints; boolean isFirst; public ViewfinderView(Context context, AttributeSet attrs) { super(context, attrs); density = context.getResources().getDisplayMetrics().density; //將像素轉換成dp ScreenRate = (int)(20 * density); paint = new Paint(); Resources resources = getResources(); maskColor = resources.getColor(R.color.viewfinder_mask); resultColor = resources.getColor(R.color.result_view); resultPointColor = resources.getColor(R.color.possible_result_points); possibleResultPoints = new HashSet<ResultPoint>(5); } @Override public void onDraw(Canvas canvas) { //中間的掃描框,你要修改掃描框的大小,去CameraManager裡面修改 Rect frame = CameraManager.get().getFramingRect(); if (frame == null) { return; } //初始化中間線滑動的最上邊和最下邊 if(!isFirst){ isFirst = true; slideTop = frame.top; slideBottom = frame.bottom; } //獲取屏幕的寬和高 int width = canvas.getWidth(); int height = canvas.getHeight(); paint.setColor(resultBitmap != null ? resultColor : maskColor); //畫出掃描框外面的陰影部分,共四個部分,掃描框的上面到屏幕上面,掃描框的下面到屏幕下面 //掃描框的左邊面到屏幕左邊,掃描框的右邊到屏幕右邊 canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); canvas.drawRect(0, frame.bottom + 1, width, height, paint); if (resultBitmap != null) { // Draw the opaque result bitmap over the scanning rectangle paint.setAlpha(OPAQUE); canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint); } else { //畫掃描框邊上的角,總共8個部分 paint.setColor(Color.GREEN); canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top + ScreenRate, paint); canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right, frame.top + CORNER_WIDTH, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top + ScreenRate, paint); canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left + ScreenRate, frame.bottom, paint); canvas.drawRect(frame.left, frame.bottom - ScreenRate, frame.left + CORNER_WIDTH, frame.bottom, paint); canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH, frame.right, frame.bottom, paint); canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate, frame.right, frame.bottom, paint); //繪制中間的線,每次刷新界面,中間的線往下移動SPEEN_DISTANCE slideTop += SPEEN_DISTANCE; if(slideTop >= frame.bottom){ slideTop = frame.top; } canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint); //畫掃描框下面的字 paint.setColor(Color.WHITE); paint.setTextSize(TEXT_SIZE * density); paint.setAlpha(0x40); paint.setTypeface(Typeface.create("System", Typeface.BOLD)); canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint); Collection<ResultPoint> currentPossible = possibleResultPoints; Collection<ResultPoint> currentLast = lastPossibleResultPoints; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new HashSet<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(OPAQUE); paint.setColor(resultPointColor); for (ResultPoint point : currentPossible) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint); } } if (currentLast != null) { paint.setAlpha(OPAQUE / 2); paint.setColor(resultPointColor); for (ResultPoint point : currentLast) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint); } } //只刷新掃描框的內容,其他地方不刷新 postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); } } public void drawViewfinder() { resultBitmap = null; invalidate(); } /** * Draw a bitmap with the result points highlighted instead of the live * scanning display. * * @param barcode * An image of the decoded barcode. */ public void drawResultBitmap(Bitmap barcode) { resultBitmap = barcode; invalidate(); } public void addPossibleResultPoint(ResultPoint point) { possibleResultPoints.add(point); } }

微信那根中間線用的是切圖,我這裡是純代碼畫的。如果想更接近原版,把這段:

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

換成:

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

那張掃描線切圖得自己從微信裡找。做法也不難:下載微信 apk,把後綴改成 zip,解壓就能拿到裡面的資源。

另外畫底部提示文字的那段建議改成下面這樣,能讓文字按實際寬度居中,視覺上舒服很多。如果文字過長需要自動換行,這裡沒做處理,可以自行補上:

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

跑起來之後,中間那根綠線會上下移動,整體觀感和微信已經相當接近。當然,別忘了在清單文件裡補上相機和振動等相關權限,動態權限在高版本系統上也需要主動申請。

從晚上八點多寫到現在,看著字不多,實際花時間不少。如果這篇對你有幫助,幫忙頂一下。項目裡還有一些資源文件沒貼出來,想看完整效果可以下載源碼。

我在另一篇《Android 基於 google Zxing 實現對手機中的二維碼進行掃描》裡還實現了對手機中二維碼照片的識別,並且替換了中間的掃描線,效果更接近微信,建議一并參考那篇文章的源碼。

以上就是本文的全部內容,希望對大家的學習或工作有所幫助。有任何疑問歡迎留言,我會及時回覆。

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