最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Unity實現(xiàn)多平臺二維碼掃描

 更新時間:2019年07月24日 15:29:49   作者:阿循  
這篇文章主要為大家詳細介紹了Unity實現(xiàn)多平臺二維碼掃描,具有一定的參考價值,感興趣的小伙伴們可以參考一下

在unity里做掃二維碼的功能,雖然有插件,但是移動端UI一般不能自定義,所以后來自已做了一個,直接在c#層掃描解析,UI上就可以自己發(fā)揮了。

上代碼:

這個是調(diào)用zxing的腳本。

using UnityEngine;
using System.Collections;
using ZXing;
using ZXing.QrCode;
 
public class QR {
  /// <summary>
  /// 解析二維碼
  /// </summary>
  /// <param name="tex"></param>
  /// <returns></returns>
  public static string Decode(Texture2D tex) {
    return DecodeColData(tex.GetPixels32(), tex.width, tex.height); //通過reader解碼 
  }
  public static string DecodeColData(Color32[] data, int w, int h) {
    BarcodeReader reader = new BarcodeReader();
    Result result = reader.Decode(data, w, h); //通過reader解碼 
    //GC.Collect();
    if (result == null)
      return "";
    else {
      return result.Text;
    }
  }
  /// <summary>
  /// 生成二維碼
  /// </summary>
  /// <param name="content"></param>
  /// <param name="len"></param>
  /// <returns></returns>
  public static Texture2D GetQRTexture(string content, int len = 256) {
    var bw = new BarcodeWriter();
    bw.Format = BarcodeFormat.QR_CODE;
    bw.Options = new ZXing.Common.EncodingOptions() {
      Height = len,
      Width = len
    };
    var cols = bw.Write(content);
    Texture2D t = new Texture2D(len, len);
    t.SetPixels32(cols);
    t.Apply();
    return t;
  }
}

然后是封裝:

using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;
using System.Timers;
/// <summary>
/// 二維碼解析工具
/// 關(guān)鍵函數(shù):
///   public static QRHelper GetInst()                   --得到單例
///   public event Action<string> OnQRScanned;               --掃描回調(diào)
///   public void StartCamera(int index)                  --啟動攝像頭
///   public void StopCamera()                       --停止攝像頭
///   public void SetToUI(RawImage raw,int UILayoutW,int UILayoutH)     --把攝像機畫面設(shè)置到一個rawimage上并使它全屏顯示
/// </summary>
public class QRHelper {
 
  public event Action<string> OnQRScanned;
 
  private static QRHelper _inst;
  public static QRHelper GetInst() {
    if (_inst == null) {
      _inst = new QRHelper();
    }
    return _inst;
  }
  private int reqW = 640;
  private int reqH = 480;
  private WebCamTexture webcam;
 
  Timer timer_in, timer_out;
  /// <summary>
  /// 啟動攝像頭
  /// </summary>
  /// <param name="index">手機后置為0,前置為1</param>
  public void StartCamera(int index) {
    StopCamera();
    lock (mutex) {
      buffer = null;
      tbuffer = null;
    }
    var dev = WebCamTexture.devices;
    webcam = new WebCamTexture(dev[index].name);
    webcam.requestedWidth = reqW;
    webcam.requestedHeight = reqH;
    webcam.Play();
    stopAnalysis = false;
 
    InitTimer();
    timer_in.Start();
    timer_out.Start();
  }
  /// <summary>
  /// 停止
  /// </summary>
  public void StopCamera() {
    if (webcam!=null) {
      webcam.Stop();
      UnityEngine.Object.Destroy(webcam);
      Resources.UnloadUnusedAssets();
      webcam = null;
      stopAnalysis = true;
 
      timer_in.Stop();
      timer_out.Start();
      timer_in = null;
      timer_out = null;
    }
  }
  /// <summary>
  /// 把攝像機畫面設(shè)置到一個rawimage上并使它全屏顯示
  /// </summary>
  /// <param name="raw">rawimage</param>
  /// <param name="UILayoutW">UI布局時的寬度</param>
  /// <param name="UILayoutH">UI布局時的高度</param>
  public void SetToUI(RawImage raw,int UILayoutW,int UILayoutH){
    raw.GetComponent<RectTransform>().sizeDelta = GetWH(UILayoutW,UILayoutH);
    int d = -1;
    if (webcam.videoVerticallyMirrored) {
      d = 1;
    }
    raw.GetComponent<RectTransform>().localRotation *= Quaternion.AngleAxis(webcam.videoRotationAngle, Vector3.back);
    float scaleY = webcam.videoVerticallyMirrored ? -1.0f : 1.0f;
    raw.transform.localScale = new Vector3(1, scaleY * 1, 0.0f);
    raw.texture = webcam;
    raw.color = Color.white;
  }
  //在考慮可能旋轉(zhuǎn)的情況下計算UI的寬高
  private Vector2 GetWH(int UILayoutW, int UILayoutH) {
    int Angle = webcam.videoRotationAngle;
    Vector2 init = new Vector2(reqW, reqH);
    if ( Angle == 90 || Angle == 270 ) {
      var tar = init.ScaleToContain(new Vector2(UILayoutH,UILayoutW));
      return tar;
    }
    else {
      var tar = init.ScaleToContain(new Vector2(UILayoutW, UILayoutH));
      return tar;
    }
  }
  private void InitTimer() {
    timer_in = new Timer(500);
    timer_in.AutoReset = true;
    timer_in.Elapsed += (a,b) => {
      ThreadWrapper.Invoke(WriteDataBuffer);
    };
    timer_out = new Timer(900);
    timer_out.AutoReset = true;
    timer_out.Elapsed += (a,b)=>{
      Analysis();
    };
  }
  private Color32[] buffer = null;
  private Color32[] tbuffer = null;
  private object mutex = new object();
  private bool stopAnalysis = false;
 
  int dw, dh;
  private void WriteDataBuffer() {
    lock (mutex) {
      if (buffer == null && webcam!=null) {
        buffer = webcam.GetPixels32();
        dw = webcam.width;
        dh = webcam.height;
      }
    }
  }
  //解析二維碼
  private void Analysis() {
    if (!stopAnalysis) {
      lock (mutex) {
        tbuffer = buffer;
        buffer = null;
      }
      if (tbuffer == null) {
        ;
      }
      else {
        string str = QR.DecodeColData(tbuffer, dw, dh);
        tbuffer = null;
        if (!str.IsNullOrEmpty() && OnQRScanned != null) {
          ThreadWrapper.Invoke(() => {
            if (OnQRScanned!=null)
              OnQRScanned(str);
          });
        }
      }
    }
    tbuffer = null;
  }
}

調(diào)用方式如下,用了pureMVC,可能理解起來有點亂,也不能直接用于你的工程,主要看OnRegister和OnRemove里是怎么啟動和停止的,以及RegQRCB、RemoveQRCB、OnQRSCcanned如何注冊、移除以及響應(yīng)掃描到二維碼的事件的。在onregister中,由于ios上畫面有鏡象,所以把rawimage的scale的y置為了-1以消除鏡像:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using PureMVC.Patterns;
using PureMVC.Interfaces;
/// <summary>
/// 掃描二維碼界面邏輯
/// </summary>
public class ScanQRMediator : Mediator {
 
  AudioProxy audio;
 public QRView TarView {
    get {
      return base.ViewComponent as QRView;
    }
  }
  public ScanQRMediator()
    : base("ScanQRMediator") {
  }
  string NextView = "";
  bool isInitOver = false;
  int cameraDelay = 1;
  public override void OnRegister() {
    base.OnRegister();
 
    if (Application.platform == RuntimePlatform.IPhonePlayer) {
      cameraDelay = 5;
    }
    else {
      cameraDelay = 15;
    }
 
    audio = AppFacade.Inst.RetrieveProxy<AudioProxy>("AudioProxy");
 
    TarView.BtnBack.onClick.AddListener(BtnEscClick);
    
    QRHelper.GetInst().StartCamera(0);
    TarView.WebcamContent.rectTransform.localEulerAngles = Vector3.zero;
    CoroutineWrapper.EXEF(cameraDelay, () => {
      RegQRCB();
      QRHelper.GetInst().SetToUI(TarView.WebcamContent, 1536, 2048);
      if (Application.platform == RuntimePlatform.IPhonePlayer) {
        TarView.WebcamContent.rectTransform.localScale = new Vector3(1, -1, 0);
      }
      isInitOver = true;
    });
    UmengStatistics.PV(TarView);
    //暫停背景音樂
    audio.SetBGActive(false);
  }
 
  public override void OnRemove() {
    base.OnRemove();
    TarView.BtnBack.onClick.RemoveListener(BtnEscClick);
    if (NextView != "UnlockView") {
      audio.SetBGActive(true);
    }
    NextView = "";
    isInitOver = false;
  }
  bool isEsc = false;
  void BtnEscClick() {
    if (isEsc || !isInitOver) {
      return;
    }
    isEsc = true;
 
    TarView.WebcamContent.texture = null;
    TarView.WebcamContent.color = Color.black;
    RemoveQRCB();
    QRHelper.GetInst().StopCamera();
 
    CoroutineWrapper.EXEF(cameraDelay, () => {
      isEsc = false;
      if (Application.platform == RuntimePlatform.IPhonePlayer) {
        ToUserInfoView();
      }
      else {
        string origin = TarView.LastArg.SGet<string>("origin");
        if (origin == "ARView") {
          ToARView();
        }
        else if (origin == "UserInfoView") {
          ToUserInfoView();
        }
        else {
          ToARView();
        }
      }
    });
  }
  void ToARView() {
    AppFacade.Inst.RemoveMediator(this.MediatorName);
    ViewMgr.GetInst().ShowView(TarView, "ARView", null);
  }
  void ToUserInfoView() {
    AppFacade.Inst.RemoveMediator(this.MediatorName);
    ViewMgr.GetInst().ShowView(TarView, "UserInfoView", null);
    var v = ViewMgr.GetInst().PeekTop();
    var vc = new UserInfoMediator();
    vc.ViewComponent = v;
    AppFacade.Inst.RegisterMediator(vc);
  }
  int reg = 0;
  void RegQRCB() {
    if (reg == 0) {
      QRHelper.GetInst().OnQRScanned += OnQRScanned;
      reg = 1;
    }
  }
  void RemoveQRCB() {
    if (reg == 1) {
      QRHelper.GetInst().OnQRScanned -= OnQRScanned;
      reg = 0;
    }
  }
  bool isQRJump = false;
  void OnQRScanned(string qrStr) {
    if (isQRJump) {
      return;
    }
    isQRJump = true;
 
    TarView.WebcamContent.texture = null;
    TarView.WebcamContent.color = Color.black;
    RemoveQRCB();
    QRHelper.GetInst().StopCamera();
    NextView = "UnlockView";
    CoroutineWrapper.EXEF(cameraDelay, () => {
      isQRJump = false;
      AppFacade.Inst.RemoveMediator(this.MediatorName);
      audio.PlayScanedEffect();
#if YX_DEBUG
      Debug.Log("qr is :"+qrStr);
      Toast.ShowText(qrStr,1.5f);
#endif
      ViewMgr.GetInst().ShowView(TarView, "UnlockView", HashtableEX.Construct("QRCode", qrStr, "origin", TarView.LastArg.SGet<string>("origin")));
      var v = ViewMgr.GetInst().PeekTop();
      var vc = new UnlockMediator();
      vc.ViewComponent = v;
      AppFacade.Inst.RegisterMediator(vc);
    });
  }
}

最后,放上zxing.unity.dll,放在plugins里就可以了。

以上代碼5.1.2測試可用。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Winform讓DataGridView左側(cè)顯示圖片

    Winform讓DataGridView左側(cè)顯示圖片

    本文主要介紹在如何讓DataGridView左側(cè)顯示圖片,這里主要講解重寫DataGridView的OnRowPostPaint方法,需要的朋友可以參考下。
    2016-05-05
  • 基于WPF實現(xiàn)篩選下拉多選控件

    基于WPF實現(xiàn)篩選下拉多選控件

    這篇文章主要為大家詳細介紹了如何基于WPF實現(xiàn)簡單的篩選下拉多選控件,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下
    2023-04-04
  • C#中文件名或文件路徑非法字符判斷方法

    C#中文件名或文件路徑非法字符判斷方法

    這篇文章主要介紹了C#中文件名或文件路徑非法字符判斷方法,本文主要使用了內(nèi)置的GetInvalidFileNameChars方法實現(xiàn)非法字符判斷,需要的朋友可以參考下
    2015-06-06
  • C#中GDI+繪制圓弧及圓角矩形等比縮放的繪制

    C#中GDI+繪制圓弧及圓角矩形等比縮放的繪制

    這篇文章主要介紹了C#中GDI+繪制圓弧及圓角矩形等比縮放的繪制,文章圍繞主題展開詳細的內(nèi)容戒殺,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • C#把EXCEL數(shù)據(jù)轉(zhuǎn)換成DataTable

    C#把EXCEL數(shù)據(jù)轉(zhuǎn)換成DataTable

    這篇文章介紹了C#把EXCEL數(shù)據(jù)轉(zhuǎn)換成DataTable的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • C#中的隨機數(shù)函數(shù)Random()

    C#中的隨機數(shù)函數(shù)Random()

    這篇文章介紹了C#生成隨機數(shù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • WPF利用ValueConverter實現(xiàn)值轉(zhuǎn)換器

    WPF利用ValueConverter實現(xiàn)值轉(zhuǎn)換器

    值轉(zhuǎn)換器在WPF開發(fā)中是非常常見的,值轉(zhuǎn)換器可以幫助我們很輕松地實現(xiàn),界面數(shù)據(jù)展示的問題。本文將通過WPF?ValueConverter實現(xiàn)簡單的值轉(zhuǎn)換器,希望對大家有所幫助
    2023-03-03
  • C# 基礎(chǔ)入門--關(guān)鍵字

    C# 基礎(chǔ)入門--關(guān)鍵字

    本文主要介紹了C# 基礎(chǔ)知識--關(guān)鍵字的相關(guān)知識,具有很好的參考價值,下面跟著小編一起來看下吧
    2017-03-03
  • 如何在C#中使用只讀的 Collections

    如何在C#中使用只讀的 Collections

    這篇文章主要介紹了如何在C#中使用只讀的 Collections,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-04-04
  • 淺析c#范型中的特殊關(guān)鍵字where & default

    淺析c#范型中的特殊關(guān)鍵字where & default

    以下是對c#范型中的特殊關(guān)鍵字where和default進行了詳細的介紹,需要的朋友可以過來參考下
    2013-09-09

最新評論

辉南县| 姜堰市| 金寨县| 广东省| 西盟| 彭山县| 林甸县| 福贡县| 酉阳| 阳曲县| 通海县| 南京市| 张家界市| 吐鲁番市| 泸溪县| 阳谷县| 鄱阳县| 桂东县| 洞头县| 高密市| 海盐县| 贡山| 城固县| 峨眉山市| 盈江县| 固原市| 邵阳县| 永新县| 建湖县| 海兴县| 平塘县| 花垣县| 鞍山市| 大冶市| 巴里| 元阳县| 朝阳县| 伊宁县| 灵丘县| 翁源县| 永嘉县|