ionic3 使用QR Scaner 扫描

作者: No刹那光辉 | 来源:发表于2018-01-08 17:15 被阅读1735次

ionic 官方有提供三个扫描插件,分别为:

  1. Barcode Scanner
    速度很慢,样式不怎样
  2. QR Scanner
    速度快,样式随心所欲,直接在html里修改属于自己的样式
  3. ZBar
    速度快,能扫描条形码与二维码,这样也导致如果二维码附近有其它类似一维码的图案,可能会影响值的准确性,还有没有提供扫描框

综合以上,所以最后还是决定使用QR Scaner进行扫描。

1. 安装插件
$ ionic cordova plugin add cordova-plugin-qrscanner
$ npm install --save @ionic-native/qr-scanner
2. 新建扫描页面
$ ionic g page scan

成功后


图片.png
3. 使用

assets/imgs
扫描框图片做css背景
下载图片

图片.png

scan.html

<ion-header >
  <ion-navbar >
      <ion-title>扫描中……</ion-title>
  </ion-navbar>
</ion-header>
<ion-content no-scroll class="qrscanner" >
  <div class="qrscanner-area">    
  </div> 
   <div class="through-line"></div>
  <div class="button-bottom">
      <button (click)="toggleLight()" ion-fab class="icon-camera" margin-right>
          <ion-icon name="flash"></ion-icon>                  
      </button>
      <button (click)="toggleCamera()" ion-fab class="icon-camera">
          <ion-icon name="reverse-camera"></ion-icon>                  
      </button>
  </div>    
</ion-content>

scan.scss

page-scan {
.qrscanner {
    background: none;
    &-area {
      width: 100%;
      height: 86%;
      background: url(../assets/imgs/scanner.svg) no-repeat center center;
      background-size: contain;
    }
  }
  .through-line {
    left: 25%;
    width: 50%;
    height: 2px;
    background: red;
    position: absolute;
    animation: myfirst 2s linear infinite alternate;
  }
  @keyframes myfirst {
    0% {
      background: red;
      top: 30%;
    }
    25% {
      background: yellow;
      top: 35%;
    }
    50% {
      background: blue;
      top: 40%;
    }
    75% {
      background: green;
      top: 45%;
    }
    100% {
      background: red;
      top: 50%;
    }
  }
  .button-bottom {
    width: 128px;
    position: absolute;
    left: 50%;
    bottom: 80px;
    margin-left: -64px;
    .icon-camera {
      float: left;
    }
}
}

scan.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';

/**
 * Generated class for the ScanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-scan',
  templateUrl: 'scan.html',
})
export class ScanPage {
  light: boolean;//判断闪光灯
  frontCamera: boolean;//判断摄像头

  constructor(
    private navCtrl: NavController,
    private navParams: NavParams,
    private qrScanner: QRScanner,
    private viewCtrl: ViewController) {
      //默认为false
      this.light = false;
      this.frontCamera = false;
  }

  ionViewDidLoad() {
    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          // camera permission was granted
          // start scanning
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            alert(text);      
            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
            this.navCtrl.pop();
          });

          // show camera preview
          this.qrScanner.show();

          // wait for user to scan something, then the observable callback will be called
        } 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
        } 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));
  }

  ionViewDidEnter(){
    //页面可见时才执行
    this.showCamera();
  }



  /**
   * 闪光灯控制,默认关闭
   */
  toggleLight() {
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.light = !this.light;
  }

  /**
   * 前后摄像头互换
   */
  toggleCamera() {
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.frontCamera = !this.frontCamera;
  }

  showCamera() {
    (window.document.querySelector('ion-app') as HTMLElement).classList.add('cameraView');
  }
  hideCamera() {    
    this.qrScanner.hide();//需要关闭扫描,否则相机一直开着
    (window.document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView');
  }

  ionViewWillLeave() {
    this.hideCamera();
  }
}

variables.scss

ion-app.cameraView, ion-app.cameraView ion-content, ion-app.cameraView .nav-decor {
  background: transparent none !important; 
  .tabbar.show-tabbar{
    opacity: 0;
  }
}
最后在所需的页面跳转scan页面即可
this.navCtrl.push('ScanPage');
4. 效果
1.gif
5. android版本仍黑屏问题

当你以上设置完后,运行在android手机上背景无法透明,依然显示黑屏的情况,主要是ionic css的结构被改变过,所以代码所设置的样式无法生效,例如安装了cordova-plugin-crosswalk-webview无法正确显示相机画面。把它删除即可

相关文章

网友评论

  • 我是要成为海贼王de女人:请问大佬QR Scaner 如何连续扫描多个二维码啊?
  • 443b90daef82:楼主,iOS端的扫描条形码不行。
    已经修改了参数类型
    metaOutput!.metadataObjectTypes = metaOutput!.availableMetadataObjectTypes
  • 0d500f51be76:ios扫码会出现黑屏。index.html <ion-app style="background: none transparent;"></ion-app>已添加。variables.scss 也添加样式。安卓的正常,iOS不行,有指导下的吗?
  • f6adf7681982:ios扫码会出现黑屏。index.html <ion-app style="background: none transparent;"></ion-app>已添加。variables.scss 也添加样式。重要的是and一切正常。请问这是什么情况,大佬,还需要设置什么样式吗?
    f6adf7681982:@鱼鱼2323 没有呢。同求
    0d500f51be76:兄弟我和你一样的问题,有解决吗?
  • 差不多先生_2517:会在打包时候出现
  • 差不多先生_2517:今天安装了这个,发现androidmanifest中的camera权限重复问题,在github issue中也有人出现过,不知道大神们怎么解决,上不了图:sweat:
  • 7a4d992c1bd3:我在用你这些代码的时候,扫描框延迟消失,不跟着页面一块消失,怎么解决
  • ftmo:小白福利
  • 98d7573c754e:variables.scss 这一步操作是什么意思啊?
  • 2588ad5b79c2:我这个扫描页面是白屏,不显示摄像头~
    2588ad5b79c2:@Seven昔年_505c 解决了,是样式设置的问题,因为我嵌套了tabs的模板
    98d7573c754e:我的也出现了一样的问题你有解决么?
  • 40ff39489929:楼主请教一下,为什么没有用ordova-plugin-crosswalk-webview这个插件,ion-app上也写了background:transparent,但是手机测试的时候还是黑屏
  • _听风细雨:楼主请教一下,使用hide相机没有关闭怎么解决的呀。
  • 93ff9d882327:core.js:1350 ERROR Error: Uncaught (in promise): Error: Template parse errors:
    Parser Error: Missing expected } at the end of the expression [{'qrscanner':isShow] in ng:///ScanPageModule/ScanPage.html@11:23 ("
    </ion-navbar>
    </ion-header>
    <ion-content no-scroll [ERROR ->][ngClass]="{'qrscanner':isShow" >
    <div [ngClass]="{'qrscanner-area':isShow}">
    </div>
    "): ng:///ScanPageModule/ScanPage.html@11:23
    Parser Error: Missing expected } at the end of the expression [{'qrscanner':isShow] in ng:///ScanPageModule/ScanPage.html@11:23 ("
    </ion-navbar>
    </ion-header>
    这个问题楼主有遇到过吗
    No刹那光辉:@时政 改好了,html上写少一个}😁
  • 告爬子:compiler.js:486 Uncaught Error: Template parse errors:
    Parser Error: Missing expected } at the end of the expression [{'qrscanner':isShow] in ng:///AppModule/ScanPage.html@5:23 ("
    </ion-navbar>
    </ion-header>
    <ion-content no-scroll [ERROR ->][ngClass]="{'qrscanner':isShow" >
    <div [ngClass]="{'qrscanner-area':isShow}">
    </div>
    "): ng:///AppModule/ScanPage.html@5:23
    Parser Error: Missing expected } at the end of the expression [{'qrscanner':isShow] in ng:///AppModule/ScanPage.html@5:23 ("
    </ion-navbar>
    </ion-header>
    按照大佬写法报错了,这是什么原因,大佬看一下:fearful:
    告爬子:@时政 你也在做ionic项目么,加个企鹅交流交流鲁:joy:
    No刹那光辉:@告爬子 改好了,html上写少一个}
    93ff9d882327:你解决了吗,我也遇到这个问题
  • 29ce5f2ac03c:我扫描之后返回上一页我得摄像头还是开着,是hide无效吗
    No刹那光辉:@卤蛋在奔跑 把代码贴出来吧,让后面的人能看到
    29ce5f2ac03c:执行了,我添加了destroy才关闭了摄像头
    No刹那光辉:@卤蛋在奔跑 是没执行到吧?
  • 9e335a5024ea:hide之后,相机好像还开着,这个问题我没找到解决办法,有什么兼容问题吗
    9e335a5024ea:@卤蛋在奔跑 没有,还是这样,用了destroy还是有问题,估计和其它插件起冲突了,你解决了没?
    vowor:调用.destroy();销毁 就关闭了
    29ce5f2ac03c:您好。我也遇到了这个问题,请问你解决了吗
  • 9e335a5024ea:学习了
  • 海货:我用的这个代码没问题;
    再问一下:header能不能让它透明
    海货:@No刹那光辉 你的这篇文章质量很高
    海货:@No刹那光辉 改了改有点儿问题
    No刹那光辉:@海货 这些html不是随你自己控制么
  • No刹那光辉:@张江是个地名 试下看能否正常拍照,是否没权限
  • 雪空不空:你好,请问一下,我这边测试了一下,打包测试包没有问题,加上--prod参数的话,就会报异常,模块未找到,请问是什么问题呢
  • 45fd031da4f1:请问 qrScanner是不是不支持barcode的识别呀?
    b1eb368950d2:经测试,稍微调整下插件的源码就可支持barcode。iOS:QRScanner.swift中153行改成metaOutput!.metadataObjectTypes = [AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeQRCode]以及241行改成if [AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeQRCode].contains(found.type) && found.stringValue != nil {
    即可支持barcode;
    安卓部分在QRScanner.java的458行添加一个barcode的类型即可
    No刹那光辉:qr qr 嘛,更何况测试是最好的答案
  • 5cfa291f8906:您好,我想问下这个怎么设置连扫?不要每次扫描都退出扫描界面
    5cfa291f8906:@No刹那光辉 太感谢了,试了下,还真可以.谢谢
    No刹那光辉:pop注释掉
  • eddb3688d380:你好 楼主 我项目内用modal.present()这个返回或跳转的页面时,扫描页面的背景就变成了用modal.present()的页面,而且项目内有些页面必须用modal,这怎么解决??刚入门,求解,谢谢
  • llcheng:你好,我使用你的代码可以扫描二维码了,但是在扫码界面返回后只有一个首页,不再显示tabs,请问这种要怎么弄。
  • 47063e58b33f:您好,现在我的项目安卓6.0以下必须要装cordova-plugin-crosswalk-webview,但是这个插件就如你所说的跟cordova-plugin-qrscanner有冲突导致黑屏,请问该如何解决这个问题?
    47063e58b33f:@No刹那光辉 可以了,万分感谢:+1::+1::+1:
    No刹那光辉:尝试在config.xml中添加
    <preference name="CrosswalkAnimatable" value="true" />
    试下看能否解决
  • fc778d3c18ec:运行在android手机上背景无法透明,依然显示黑屏的情况,但是我没有装cordova-plugin-crosswalk-webview,还有什么插件冲突的?
    我的插件列表:
    "cordova": {
    "plugins": {
    "ionic-plugin-keyboard": {},
    "cordova-plugin-whitelist": {},
    "cordova-plugin-device": {},
    "cordova-plugin-splashscreen": {},
    "cordova-plugin-ionic-webview": {},
    "cordova-plugin-camera": {},
    "com.synconset.imagepicker": {
    "PHOTO_LIBRARY_USAGE_DESCRIPTION": "your usage message"
    },
    "cordova-sqlite-storage": {},
    "cordova-plugin-file-opener2": {},
    "cordova-hot-code-push-plugin": {},
    "cordova-plugin-qrscanner": {},
    "cordova-android-support-gradle-release": {
    "ANDROID_SUPPORT_VERSION": "27.+"
    }
    },
    帮忙看下是哪里有问题?
    No刹那光辉:@愛七戒 创建的项目是tabs还是menu这样的项目都有关系的,目前这个我只在tabs,menu上试过
  • d7431d3aac51:您好,非常感谢您的分享,我想问下为什么我手机链接主页,有扫描画面,但没有打开相机,手机和电脑在一个局域网里面。初学者,多多包含。
    No刹那光辉:@ppld 浏览器是不能使用扫描的
    d7431d3aac51:@No刹那光辉 用手机实现扫码 ,具体是怎么操作呢,现在我用的是浏览器调试的
    No刹那光辉:@cxdkl 网页打开?
  • 清丶虹:华为手机第一次进入扫码页面会导致上一个堆栈页面和扫码页面同时出现
    No刹那光辉:把二维码页面懒加载去掉,控制好生命周期,应该不会有问题
  • 0d2d50f28f1f:老哥,安装QR Scanner会报错,然后用xcode9打包会报版本不符,我现在用的是ionicCLI3.19.1 Ionic Framework : ionic-angular 3.9.2 cordova 8.0.0 cordova-ios4.5.4
    No刹那光辉:@hiMonkey_774a 把cordova降级到6.x试试吧
  • 壹点微尘:需要在app.scss设置下下面的样式,不然ios显示不出来
    https://github.com/bitpay/cordova-plugin-qrscanner/issues/125
    in app.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; }
    壹点微尘:@No刹那光辉 还真的是没配置 variables.scss:joy:
    No刹那光辉:@壹点微尘 你是不是忘配置variables.scss那一步了,我试过安卓真机设置mode:ios模式,ios真机都可行的
    No刹那光辉:variables.scss里写是一样的道理
  • 胖子饭店:上班时间偷偷写文章,我要向你领导...表扬你的刻苦钻研精神
    No刹那光辉:@胖子饭店 黑色就是我老板来的,他叫我写的:smile:

本文标题:ionic3 使用QR Scaner 扫描

本文链接:https://www.haomeiwen.com/subject/xoybnxtx.html