如何将类型"UnityEngine.Color32[ ]"转换为"UnityEngine.Sprite"



我试图使用ZXing.Net生成一个QR码,起初我遇到了.Save()由于错误CS1061而无法工作的问题。所以,我放弃了这个想法,然后我试图将.Write()保存为图像,然后在unity中渲染它,但unity返回了一个错误:

Cannot implicitly convert type 'UnityEngine.Color32[]' to 'UnityEngine.Sprite'

我尝试使用这里的答案,他们使用Sprite.Create()作为解决方案,但转换了Texture2D而不是Color32[],但我无法确认代码是否对我有效,因为代码返回了一个错误:

The type or namespace name 'Image' could not be found

正如我所说,我无法确定代码是否真的有效。我不知道是什么原因导致了namespace错误,因为我使用的脚本在图像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();
}

我还没有测试过这个代码,因为在运行之前必须先解决错误。

第一个

找不到类型或命名空间名称"Image">

通过添加相应的命名空间来修复

using UnityEngine.UI;

在文件的顶部。


异常

无法将类型"UnityEngine.Color32[]"隐式转换为"UnityEngine.Sprite">

不能简单地"固定"。正如异常告诉你的那样:你不能在这些类型之间隐式转换。。甚至不明确。

qrWriter.Write("text");

返回CCD_ 7。


您可以尝试使用此颜色信息创建纹理,但您必须始终了解目标纹理的像素尺寸

然后你可以像一样使用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才能设置所需的像素尺寸,如本博客所示:

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();

在那里你还可以找到一些关于纹理的线程和缩放等更有用的信息。

using UnityEngine;
public class ExampleScript : MonoBehaviour
{
WebCamTexture webcamTexture;
Color32[] data;
public UIScreen screen;
int HEIGHT, WIDTH;
void Start()
{
// Start web cam feed
webcamTexture = new WebCamTexture();
webcamTexture.Play();
HEIGHT = webcamTexture.height;
WIDTH = webcamTexture.width;
data = new Color32[WIDTH * HEIGHT];
}
void Update()
{
if (webcamTexture.didUpdateThisFrame)
{
webcamTexture.GetPixels32(data);
var texture = new Texture2D(WIDTH, HEIGHT);
texture.SetPixels32(data);
texture.Apply();
screen.imageUI.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f, 100);
}
}
}

incase if anyone needs the entire code to convert and show webcam to imageUI/spritescreen.imageUI is just the Image ui element in canvas

相关内容

最新更新