我正在尝试使用ZXing.Net生成QR码,首先我遇到的问题是.Save()
由于CS1061错误而无法正常工作。因此,我ed了这个想法,然后尝试将.Write()
保存为图片,然后统一渲染,但是Unity返回错误:
Cannot implicitly convert type 'UnityEngine.Color32[]' to 'UnityEngine.Sprite'
我尝试使用see screenshot的答案,其中他们使用Sprite.Create()
作为解决方案,但转换了Texture2D而不是Color32 [],但是由于该代码对我来说不起作用,因此我无法确认该代码返回以下错误:
The type or namespace name 'Image' could not be found
正如我所说,我无法确定代码是否真的有效。我不知道是什么原因导致了namespace
错误,因为我正在使用的脚本在Image UI下。
这些是我正在使用的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZXing;
using ZXing.QrCode;
using System.Drawing;
public class SampleScript : MonoBehaviour
{
public Texture2D myTexture;
Sprite mySprite;
Image myImage;
void Main()
{
var qrWriter = new BarcodeWriter();
qrWriter.Format = BarcodeFormat.QR_CODE;
this.gameObject.GetComponent<SpriteRenderer>().sprite = qrWriter.Write("text");
}
public void FooBar()
{
mySprite = Sprite.Create(myTexture, new Rect(0.0f, 0.0f, myTexture.width, myTexture.height), new Vector2(0.5f, 0.5f), 100.0f);
myImage.sprite = mySprite;
}
void Start()
{
FooBar();
Main();
}
我仍然没有测试此代码,因为必须先解决错误,然后再运行。
答案 0 :(得分:1)
第一个
找不到类型或名称空间名称'Image'
通过添加相应的名称空间进行修复
using UnityEngine.UI;
位于文件顶部。
例外
无法将类型'UnityEngine.Color32 []'隐式转换为'UnityEngine.Sprite'
不能简单地“修复”。就像异常告诉您的那样:您不能在这些类型之间隐式转换..甚至不能显式。
qrWriter.Write("text");
返回Color32[]
。
您可以尝试使用此颜色信息但创建纹理,否则您将必须知道目标纹理的像素尺寸。
然后您可以像使用Texture2D.SetPixels32
var texture = new Texture2D(HIGHT, WIDTH);
texture.SetPixels32(qrWriter.Write("text"));
texture.Apply();
this.gameObject.GetComponent<SpriteRenderer>().sprite = Sprite.Create(texture, new Rect(0,0, texture.width, texture.height), Vector2.one * 0.5f, 100);
可能还必须积极传递EncodingOptions
才能设置所需的像素尺寸,如this blog所示:
using ZXing.Common; ... BarcodeWriter qrWriter = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = height, Width = width } }; Color32[] pixels = qrWriter.Write("text"); Texture2D texture = new Texture2D(width, height); texture.SetPixels32(pixels); texture.Apply();
您还可以找到有关纹理的线程化和缩放等更多有用的信息。