本文將講解一下我最近寫的一個(gè)快速集成二維碼掃描庫(kù),這里需要說(shuō)明的是其核心的實(shí)現(xiàn)掃描的功能,是通過(guò)調(diào)用ZXing庫(kù)實(shí)現(xiàn)的。內(nèi)部App中使用到了二維碼掃描功能,但是網(wǎng)上找了一些關(guān)于二維碼掃描的例子,只是我在集成的時(shí)候發(fā)現(xiàn)通過(guò)android studio集成zxing二維碼庫(kù)不是特別方便,由于我就有了將其制作成標(biāo)準(zhǔn)庫(kù)的想法,也就有了本文即快速集成二維碼掃描庫(kù)。
本文的項(xiàng)目地址是在: android-zxingLibrary ,歡迎star和follow。
使用方式:
集成默認(rèn)的二維碼掃描頁(yè)面
在具體介紹該掃描庫(kù)之前我們先看一下其具體的使用方式,看看是不是幾行代碼就可以集成二維碼掃描的功能。
在module的build.gradle中執(zhí)行compile操作
compile 'cn.yipianfengye.android:zxing-library:1.1'
在代碼中執(zhí)行打開(kāi)掃描二維碼界面操作
/**
* 打開(kāi)默認(rèn)二維碼掃描界面
*/
button1.setOnClickListener(new View.OnClickListener() {
[email protected]
public void alt="物聯(lián)網(wǎng)" width="320" height="565" />
但是這樣的話是不是太簡(jiǎn)單了,如果我想選擇圖片解析呢?別急,對(duì)二維碼圖片的解析也是支持的
集成對(duì)二維碼圖片的解析功能
調(diào)用系統(tǒng)API打開(kāi)圖庫(kù)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
在Activity的onActivityResult方法中獲取用戶選中的圖片并調(diào)用二維碼圖片解析API
if (requestCode == REQUEST_IMAGE) {
if (data != null) {
Uri uri = data.getData();
ContentResolver cr = getContentResolver();
try {
Bitmap mBitmap = MediaStore.Images.Media.getBitmap(cr, uri);//顯得到bitmap圖片
CodeUtils.analyzeBitmap(mBitmap, new CodeUtils.AnalyzeCallback() {
[email protected]
public void alt="物聯(lián)網(wǎng)" width="320" height="565" />
有了默認(rèn)的二維碼掃描界面,也有了對(duì)二維碼圖片的解析,可能有的同學(xué)會(huì)說(shuō)如果我想定制化顯示UI怎么辦呢?沒(méi)關(guān)系也支持滴。
定制化顯示掃描UI
由于我們的掃描組件是通過(guò)Fragment實(shí)現(xiàn)的,所以能夠很輕松的實(shí)現(xiàn)掃描UI的定制化。
在新的Activity中定義Layout布局文件
android:id="@+id/activity_second"
android:layout_width="match_parent"
android:layout_height="match_parent">
<button< p="">
android:id="@+id/second_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:layout_gravity="bottom|center_horizontal"
/>
<framelayout< p="">
android:id="@+id/fl_my_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
啟動(dòng)id為fl_my_container的FrameLayout就是我們需要替換的掃描組件,也就是說(shuō)我們會(huì)將我們定義的掃描Fragment替換到id為fl_my_container的FrameLayout的位置。而上面的button是我們添加的一個(gè)額外的控件,在這里你可以添加任意的控件,各種UI效果等。具體可以看下面在Activity的初始化過(guò)程。
在Activity中執(zhí)行Fragment的初始化操作
[email protected]
protected void encoding="utf-8"?-->
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<surfaceview< p="">
android:id="@+id/preview_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.uuzuche.lib_zxing.view.viewfinderview< p="">
android:id="@+id/viewfinder_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:inner_width="180"
app:inner_height="180"
app:inner_margintop="180"
/>
上面我們自定義的掃描控件的布局文件,下面我們看一下默認(rèn)的掃描控件的布局文件: