1. 程式人生 > >ionic3 二維碼掃描外掛 (Barcode Scanner 和 Zbar和 QR Scanner)的戰鬥

ionic3 二維碼掃描外掛 (Barcode Scanner 和 Zbar和 QR Scanner)的戰鬥

三款ionic的掃描外掛。

各大部落格都有他們的介紹,我也不想贅述多少。

總結了下各大博主說的,反正是好壞都有,我給各位列個表格自己判斷吧

Barcode Scanner 速度慢,樣式機會為零
Zbar 速度快,ios樣式幾乎為零(槽點:連文字和木紋都會被掃描出資訊被我們專案總監笑了多久。。。尷尬)
QR Scanner 速度快,(點評:先抑後揚款掃描,好的東西都是最後說的,最重要是樣式可定製。)

話不多說,用外掛肯定用好的,最穩定的。先上圖

第一步:

$ ionic cordova plugin add cordova-plugin-qrscanner
$ npm install --save @ionic-native/qr-scanner

以上兩條是安裝外掛命令

第二步:

<ion-app style="background: none transparent;"></ion-app>

就是這個鬼東西,是在dom元素最底層,必須加一個透明通道。

第三步:

1)ts檔案

ionViewDidLoad() {

this.qrScanNerMethod();

}

/**

* 【手機掃描方法qrscanner外掛】

* @param{object} callBack

*/

public qrScanNerMethod(callBack?: any): void {

this.qrScanner.prepare()

.then((status:QRScannerStatus) => {

if (status.authorized) {

// 相機掃描資訊承諾

// 開始掃描

let scanSub = this.qrScanner.scan().subscribe((text:string) => {

//alert(text);

console.log("deatilText",text);

this.qrScanner.hide();// 隱藏相機

scanSub.unsubscribe();// 停止掃描事件

callBack &&callBack(1,text);

});

// 顯示相機預覽

this.qrScanner.show();

callBack &&callBack(2);

// 等待使用者掃描某個東西,然後就會呼叫可觀察的回撥

} else if (status.denied) {

// camera permission was permanently denied

// you must use QRScanner.openSettings() method to guide the user to the settings page

// then they can grant the permission from there

callBack &&callBack(3);

} else {

// permission was denied, but not permanently. You can ask for permission again at a later time.

}

})

.catch((e:any) => console.log('Error is',e));

}

/**

* 切換燈光

*/

public toggleLight(): void {

this.light = !this.light;

if (this.light) {

this.qrScanner.enableLight();

} else {

this.qrScanner.disableLight();

}

}

/**

* 切換相機

*/

public toggleCamera(): void {

this.light =true;

this.frontCamera = !this.frontCamera;

if (this.frontCamera) {

this.qrScanner.useFrontCamera();

} else {

this.qrScanner.useBackCamera();

}

}

2)css檔案

自己寫,不會就去看別人的

3)html檔案

自己寫,不會就用別人的

4.第四步,

ios相容問題,記得在全域性樣式裡面加入下面樣式,不然看不到攝像頭我可不管(app.scss或者variables.scss)

html,

body.transparent-body,

.transparent-body,

.transparent-body ion-app,

.transparent-body .app-root,

.transparent-body ion-nav,

.transparent-body .ion-page,

.transparent-body .nav-decor,

.transparent-body ion-content,

.transparent-body .viewscan,

.transparent-body .fixed-content,

.transparent-body .scroll-content {

background-color: transparent !important;

background: transparent!important;

}

然後就可以打包了,看看效果吧介面

如果不行可以給我留言,讓我看看是誰這麼棒棒這樣清楚的文件都整不出來!!!

後續:因為測試中發現了一個bug...

當二維碼掃描外掛結束,退出頁面後相機沒有關閉的問題,在ionic或者angular 的生命週期內加入一個方法

/**

* 銷燬事件

*/

public ionViewDidLeave() {

console.log("銷燬相機");

this.qrScanner.hide(); // 隱藏相機

this.qrScanner.destroy();//銷燬相機

}

我使用的是ionic的頁面關閉後出發銷燬相機事件.