編輯:關於 Android 程式設計
二維碼掃描幾乎成了 App 的標準配備,而 Google 的 ZXing 是最常被採用的開源方案,可到 https://code.google.com/p/zxing/ 下載原始碼與 Jar 包。
問題是,ZXing 預設的掃描頁實在稱不上好看。功能做得出來、介面卻讓使用者卻步,等於白做。本文記錄了把預設 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),掃描結果與截到的影像都會傳進來。/**
* 處理掃描結果
*/
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,內含預覽用的 SurfaceView、自繪的 ViewfinderView,再用 include 把標題列併進來:
<?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>
標題列另外獨立成一個檔案,因為專案裡其他頁面也共用:
<?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:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="2dip"
android:background="@drawable/mm_title_back_btn"
android:text="返回"
android:textColor="@android:color/white" />
<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>
MainActivity 很單純:一顆按鈕、一個顯示文字用的 TextView、一個顯示截圖的 ImageView。用 startActivityForResult 跳轉,回來時在 onActivityResult 取值。
<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>
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);
// 點擊按鈕跳轉到二維碼掃描界面
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;
}
}
}
光有上面的程式碼還做不出微信那種質感,必須自己畫取景框。微信用的是圖片素材,這裡改用 Canvas 直接繪製,註解寫得比較完整:
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;
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) {
// 掃描成功後,把截圖鋪在掃描框位置
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);
// 繪制中間那條線,每次刷新往下移動
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();
}
/**
* 掃描成功後,用截圖取代即時預覽
*/
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 裡撈:把 .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.scan_text);
float textWidth = paint.measureText(text);
canvas.drawText(text, (width - textWidth) / 2,
(float) (frame.bottom + (float) TEXT_PADDING_TOP * density), paint);



最後提醒兩件事:一是別忘了在 Manifest 加上相機權限,否則預覽一片黑;二是 postInvalidateDelayed 只重繪掃描框範圍,是為了省電,改成整頁 invalidate() 反而會拖慢幀率。
以上就是完整的改造流程,希望對正在做掃碼功能的你有所幫助。
Android 數據庫開發(一):SQLite3 概述與架構剖析
前言 SQLite 是一款輕量級的關聯式資料庫管理系統,遵循 ACID 特性,整個引擎被收攏在一個體積相當小的 C 函式庫裡。它由 D. Richard Hipp 建立並
Android 高德地圖自動定位實作
和其他地圖 SDK 一樣,都要先去官網註冊成為開發者,然後取得 Key。下面直接上程式碼。效果圖:核心思路是:透過系統的 LocationManager 取得定位資料,再
Android Studio Gradle 配置詳解大全
AppExtension 類及其屬性 大部分人看到 AppExtension 這個類可能會感到非常陌生,但其實我們在 app 的 build.gradle 中填寫配置信息
餘額寶與微信理財通哪個好?額度、到帳與收益比較
餘額寶與微信理財通各有優勢。餘額寶可直接消費購物,轉出額度與到帳時間較成熟;理財通操作入口方便,收益在部分時期較高。 選擇時可看流動性、額度、收益率與使用習慣。