您的位置:首页 > 移动开发 > Unity3D

unity3d生成二维码的研究

2016-01-22 13:38 435 查看
最近看了关于unity生成二维码的功能,感觉有意思就研究分享一下:

我这里用到GUI和UGUI来实现了一次,代码网上都有,我这里也是借用一下,NGUI其实也是一样,我这里就不弄了。首先下载ZXing.Net.0.12.0.0.zip,下载地址为http://zxingnet.codeplex.com/

然后找到其中的unity文件夹,将文件夹放到Unity的工程内。创建一个Raw Image ,这里介绍一下,应为image不支持Texure2d图片,我这里生成的图片是这个,所以只能用Raw Image。将代码挂在一个物体上(空物体就行),具体代码:
using UnityEngine;
using System.Collections;
using ZXing;//引入库
using ZXing.QrCode;
using UnityEngine.UI;

public class BarcodeCam : MonoBehaviour
{
//定义Texture2D对象和用于对应网站的字符串
public Texture2D encoded;
public string Lastresult;
//定义一个UI,来接收图片
public RawImage ima;
void Start()
{
encoded = new Texture2D(256, 256);
Lastresult = "http://www.qq.com";
}

//定义方法生成二维码
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);
}

void Update()
{
var textForEncoding = Lastresult;
if (textForEncoding != null)
{
//二维码写入图片
var color32 = Encode(textForEncoding, encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
//生成的二维码图片附给RawImage
ima.texture = encoded;
}
}

//将图片画出来
void OnGUI()
{
GUI.DrawTexture(new Rect(100, 100, 256, 256), encoded);
}

}
这样就可以了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity 二维码 c# ui