赞
踩
ZXing下载地址:https://archive.codeplex.com/?p=zxingnet
下载之后把unity目录下三个文件放到unity工程Plugins下,然后创建脚本:
over
using UnityEngine; using System.Collections; using ZXing; using ZXing.QrCode; using UnityEngine.UI; using System.IO; public class QRcodeDraw : MonoBehaviour { public Texture2D encoded; //指定字符串 //private string datapath = "C:/Users/ASUS/Desktop/"; public string QRCodes = "www.baidu.com"; public RawImage QRImage; private string filespath = "C:/Users/ASUS/Desktop/222.png"; private string folderpath = "C:/Users/ASUS/Desktop/"; void Start() { ShowCode(); } //定义方法生成二维码 private static Color32[] Encode(string textForEncoding, int width, int height) { var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write(textForEncoding); } public void ShowCode() { encoded = new Texture2D(256, 256); var textForEncoding = QRCodes; if (textForEncoding != null) { //二维码写入图片 var color32 = Encode(textForEncoding, encoded.width, encoded.height); encoded.SetPixels32(color32); encoded.Apply(); //重新赋值一张图,计算大小,避免白色边框过大 Texture2D encoded1; encoded1 = new Texture2D(190, 190);//创建目标图片大小 encoded1.SetPixels(encoded.GetPixels(32, 32, 190, 190)); encoded1.Apply(); QRImage.texture = encoded1; DoPicture(); } } void DoPicture()//存储为png { if (!File.Exists(filespath))//首先判断一下该图片文件是否存在 { if (!Directory.Exists(folderpath))//再判断一下该文件夹是否存在,若不存在先创建 { Directory.CreateDirectory(folderpath);//创建目录 } var bys = encoded.EncodeToPNG();//转换图片资源 File.WriteAllBytes(filespath, bys);//保存图片到写好的目录下 } } // void OnGUI() // { // GUI.DrawTexture(new Rect(100, 100, 256, 256), encoded1); // } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。