最近这两天在研究安卓机扫描二维码的原理,将研究的东西分析总结下:
首先,要进行二维码扫描就必须用到相机来扫描,先来看看安卓相机提供了哪些方法,在看到startPreview()这个方法时发现是个native方法,也就是说安卓会调用底层的C++代码吊起相机,这里不做深究,先来看下这个方法的介绍:
引用块内容
/**
* Starts capturing and drawing preview frames to the screen.
* Preview will not actually start until a surface is supplied
* with {@link #setPreviewDisplay(SurfaceHolder)} or
* {@link #setPreviewTexture(SurfaceTexture)}.
*
*If {@link #setPreviewCallback(Camera.PreviewCallback)},
* {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or
* {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were
* called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)}
* will be called when preview data becomes available.
*/
public native final void startPreview();
大致意思是要开启扫描就要在屏幕上绘制预览帧,但前提是必须调用setPreviewDisplay(SurfaceHolder);或者setPreviewTexture(SurfaceTexture);方法提供一个surface,看到这里,我想到了一个控件:SurfaceView,这是一个在主线程之外绘制View的控件,本身也继承自View,安卓每帧的绘制时间为16ms,当在这段时间内没有绘制完成就会在下一个16ms内绘制,这就有可能出现掉帧的现象从而引起卡顿。在确立了使用的控件之后,我又定义了一个绘制二维码扫描框的View,来提示用户将二维码放置在合适的位置进行绘制,大致分析下接下来要做的事:
布局文件:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<SurfaceView
android:id="@+id/capture_surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.zhaonongzi.qj.capture.ViewfinderView
android:id="@+id/capture_finderView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/capture_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="@dimen/ds_10"
android:background="@color/transparent"
android:text="@string/zxing_msg_default_status"
android:textColor="@color/white" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="@dimen/fs_130">
<RelativeLayout
android:id="@+id/capture_back"
android:layout_width="60dp"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="@dimen/fs_50"
android:background="@mipmap/back_n"
android:clickable="false"
android:focusable="false" />
</RelativeLayout>
<TextView
android:id="@+id/capture_text"
android:layout_width="@dimen/ds_500"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="默认标题"
android:textColor="@color/white"
android:textSize="15sp" />
</RelativeLayout>
这里定义为ViewfinderView,看下这个类所做的工作,在这里主要内容都在绘制二维码显示框,首先根据设置得到二维码区域的矩形范围, Rect frame = cameraManager.getFramingRect();
根据效果图分析:
将整个屏幕以扫描框为基准分为上下左右中五大模块进行绘制,每个区域都是一个矩形,代码如下:
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);
接下来绘制扫描框四个角上的矩形块,每个角上可以看做是两个大小一样但是有重叠的矩形框,长20px宽为10px,每两个一组,共八组:
paint.setColor(getResources().getColor(R.color.green));
//左上两个矩形
canvas.drawRect(frame.left, frame.top, frame.left + 20,
frame.top + 10, paint);
canvas.drawRect(frame.left, frame.top, frame.left + 10,
frame.top + 20, paint);
//右上两个矩形
canvas.drawRect(frame.right - 20, frame.top, frame.right,
frame.top + 10, paint);
canvas.drawRect(frame.right - 10, frame.top, frame.right,
frame.top + 20, paint);
//左下两个矩形
canvas.drawRect(frame.left, frame.bottom - 10, frame.left + 20,
frame.bottom, paint);
canvas.drawRect(frame.left, frame.bottom - 20, frame.left + 10,
frame.bottom, paint);
//右下两个矩形
canvas.drawRect(frame.right - 20, frame.bottom - 10, frame.right,
frame.bottom, paint);
canvas.drawRect(frame.right - 10, frame.bottom - 20, frame.right,
frame.bottom, paint);
中间上下浮动的扫描线绘制为:
if ((i += 5) < frame.bottom - frame.top) {
int r = 8;
mDrawable.setShape(GradientDrawable.RECTANGLE);
mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
setCornerRadii(mDrawable, r, r, r, r);
mRect.set(frame.left + 2, frame.top - 3 + i,
frame.right - 1, frame.top + 3 + i);
mDrawable.setBounds(mRect);
mDrawable.draw(canvas);
invalidate();
} else {
i = 0;
}
每隔一段时间更新下扫描的位置即可,这里基本显示绘制就完成了,接下来就是解析二维码。
这里用的是谷歌zxing包进行解析的,这里不多说代码如下:
引用块内容
/**
* Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
* reuse the same reader objects from one decode to the next.
*
* @param data The YUV preview frame.
* @param width The width of the preview frame.
* @param height The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
// yumin
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;
data = rotatedData;
PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
}
Handler handler = activity.getHandler();
if (rawResult != null) {
// Don't log the barcode contents for security.
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode in " + (end - start) + " ms");
if (handler != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult);
message.sendToTarget();
}
} else {
if (handler != null) {
Message message = Message.obtain(handler, R.id.decode_failed);
message.sendToTarget();
}
}
}
基本上大致思路就完成了,值得注意的是:在扫描过程中需要开启一个扫描线程,否则会引起主线程阻塞,还有就是记得开启使用相机的权限,否则将不会有任何效果…