【Unity】生成二维码

使用QrCode脚本插件

插件链接 https://files.cnblogs.com/files/weigangblog/QRCode.zip

 

简单的帮助类代码如下:

复制代码
using UnityEngine;
using ZXing;
using ZXing.QrCode;

    // 二维码
public class QrCodeHelper
{
    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 static Texture2D GetQrCode(string content, int height, int width)
    {
        var tex = new Texture2D(width, height);

        var color32 = Encode(content, width, height);

        tex.SetPixels32(color32);

        tex.Apply();

        return tex;
    }
}
复制代码

创建的调用代码如下:(例子为Unity输入框输入文本内容,按钮点击生成二维码)

复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class CreatQrCode : MonoBehaviour
{
    public GameObject creatView;
    public GameObject qrImageView;

    public InputField InputField;

    public Image image;
    public Button creatBtn;
    public Button exitBtn;
    public Button returnBtn;
    public string codeStr = "";
    // Use this for initialization
    void Start()
    {
        InputField.text = "I LOVE YOU";
        creatBtn.onClick.AddListener(QrCodeImage);
        returnBtn.onClick.AddListener(()=> { creatView.SetActive(true); });
        exitBtn.onClick.AddListener(()=>{ Application.Quit(); });
    }

    private void QrCodeImage()
    {
        codeStr = InputField.text;
        if (!string.IsNullOrEmpty(codeStr))
        {
            image.overrideSprite = Sprite.Create(QrCodeHelper.GetQrCode(codeStr, 256, 256), new Rect(Vector2.zero, new Vector2(256, 256)),
    image.sprite.pivot);
            creatView.SetActive(false);
        }
    }

}
复制代码

更为完整,创建自定义大小的二维码 代码如下:

复制代码
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace LiXiaoQian.Common
{
    // 二维码
    public class QrCodeHelper
    {    
        public static Color32[] Encode(string textForEncoding, int width, int height)
        {
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            options.CharacterSet = "UTF-8";
            options.Width = width;
            options.Height = height;
            options.Margin = 1;
            BarcodeWriter barcodeWriter = new BarcodeWriter
            { Format = BarcodeFormat.QR_CODE, Options = options };
            return barcodeWriter.Write(textForEncoding);
        }
        /// <summary>  
        /// 生成二维码  
        /// </summary>  
        public static Image CreatQR(Image img, string qrcode, int width, int height)
        {
            Texture2D encoded = null;
            if (width == height && width == 256)
            {
                encoded = GenerateQRCode256(qrcode, width, height);
            }
            else
            {
                encoded = GenerateQRCode(qrcode, width, height);
            }
            Sprite sprite = Sprite.Create(encoded, new Rect(0, 0, width, height),
                new Vector2(0.5f, 0.5f));
            img.sprite = sprite;
            return img;
        }
        public static RawImage CreatQR(RawImage img, string qrcode, int width, int height)
        {
            Texture2D encoded = null;
            if (width == height && width == 256)
            {
                encoded = GenerateQRCode256(qrcode, width, height);
            }
            else
            {
                encoded = GenerateQRCode(qrcode, width, height);
            }
            img.texture = encoded;
            return img;
        }

        /// <summary>
        /// 生成256的二维码
        /// </summary>
        public static Texture2D GenerateQRCode256(string str, int width, int height)
        {
            Texture2D t = new Texture2D(width, height);
            Color32[] col32 = Encode(str, width, height);
            t.SetPixels32(col32);
            t.Apply();
            return t;
        }

        /// <summary>
        /// 生成2维码 方法
        /// 经测试:能生成任意尺寸的正方形
        /// </summary>
        public static Texture2D GenerateQRCode(string qrcodeText, int width, int height)
        {
            // 编码成color32
            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>();
            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.Add(EncodeHintType.MARGIN, 1);
            hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.M);
            BitMatrix bitMatrix = writer.encode(qrcodeText, BarcodeFormat.QR_CODE, width, height, hints);
            int w = bitMatrix.Width;
            int h = bitMatrix.Height;
            Texture2D texture = new Texture2D(width, height);
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    //向右翻转90度
                    if (bitMatrix[height - 1 - y, x])
                    {
                        texture.SetPixel(x, y, Color.black);
                    }
                    else
                    {
                        texture.SetPixel(x, y, Color.white);
                    }
                }
            }
            texture.Apply();
            return texture;
        }
    }
}
复制代码

 

posted @   weigang  阅读(654)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示