unity生成二维码

我这里用到GUI和UGUI来实现了一次,下载地址为http://zxingnet.codeplex.com/,我这里已经下载好了,引用一个zxing.unity.dll,下载网址https://pan.baidu.com/s/1Gs3t3CEFP4sroFs0Km7f8Q,

然后找到其中的unity文件夹,将文件夹放到Unity的工程内。创建一个Raw Image ,这里介绍一下,应为image不支持Texure2d图片,我这里生成的图片是这个,所以只能用Raw Image。将代码挂在物体上

具体代码:

  1. using UnityEngine;  
  2. using System.Collections;  
  3. using ZXing;//引入库  
  4. using ZXing.QrCode;  
  5. using UnityEngine.UI;  
  6.   
  7. public class BarcodeCam : MonoBehaviour  
  8. {  
  9.     //定义Texture2D对象和用于对应网站的字符串  
  10.     public Texture2D encoded;  
  11.     public string Lastresult;  
  12.     //定义一个UI,来接收图片  
  13.     public RawImage ima;  
  14.     void Start()  
  15.     {  
  16.         encoded = new Texture2D(256, 256);  
  17.         Lastresult = "http://www.qq.com";  
  18.     }  
  19.   
  20.     //定义方法生成二维码  
  21.     private static Color32[] Encode(string textForEncoding, int width, int height)  
  22.     {  
  23.         var writer = new BarcodeWriter  
  24.         {  
  25.             Format = BarcodeFormat.QR_CODE,  
  26.             Options = new QrCodeEncodingOptions  
  27.             {  
  28.                 Height = height,  
  29.                 Width = width  
  30.             }  
  31.         };  
  32.         return writer.Write(textForEncoding);  
  33.     }  
  34.   
  35.   
  36.     void Update()  
  37.     {  
  38.         var textForEncoding = Lastresult;  
  39.         if (textForEncoding != null)  
  40.         {  
  41.             //二维码写入图片  
  42.             var color32 = Encode(textForEncoding, encoded.width, encoded.height);  
  43.             encoded.SetPixels32(color32);  
  44.             encoded.Apply();  
  45.             //生成的二维码图片附给RawImage  
  46.             ima.texture = encoded;  
  47.         }  
  48.     }  
  49.   
  50.     //将图片画出来  
  51.     void OnGUI()  
  52.     {  
  53.         GUI.DrawTexture(new Rect(100, 100, 256, 256), encoded);  
  54.     }  
  55.   
  56.   
  57.       
  58. }  

运行unity之后效果图为



,如果大家觉得麻烦的话,可以去草料二维码上面直接生成你想要的内容,网址为 https://cli.im/text 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值