unity3d生成二维码的研究

最近看了关于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);
    }


    
}
这样就可以了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值