二维码生成
从vs Nugets搜索ThoughtWorks.QRCode下载ThoughtWorks.QRCode.dll
private byte[] CreateQrcode(string code) { string enCodeString = code; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; qrCodeEncoder.QRCodeScale = 3; qrCodeEncoder.QRCodeVersion = 8; Bitmap bitmap = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8); //string filename = "QrCode.jpg"; //bt.Save(filename); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Jpeg); byte[] data = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, Convert.ToInt32(stream.Length)); return data; } }
上述二维码工具不适用与移动端,移动端可使用zxing插件
代码如下
public void ShowCode(string qrCode) { Texture2D qrCodeTex = new Texture2D(256, 256); if (qrCode != null) { //二维码写入图片 var color32 = CreateQrcode(qrCode, qrCodeTex.width, qrCodeTex.height); qrCodeTex.SetPixels32(color32); qrCodeTex.Apply(); qrCodeImage.texture = qrCodeTex; //重新赋值一张图,计算大小,避免白色边框过大 //Texture2D modifiedQrcode = new Texture2D(190, 190);//创建目标图片大小 //modifiedQrcode.SetPixels(qrCodeTex.GetPixels(32, 32, 190, 190)); //modifiedQrcode.Apply(); //qrCodeImage.texture = modifiedQrcode; } } //定义方法生成二维码 private Color32[] CreateQrcode(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); }