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

How to convert type 'UnityEngine.Color32[ ]' to 'UnityEngine.Sprite'

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

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

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

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

我还没有测试这段代码,因为必须先解决错误 运行。

第一个

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

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

using UnityEngine.UI;

在文件的顶部。


异常

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

不能简单地"fixed"。正如异常告诉您的那样:您不能在这些类型之间隐式转换..甚至不能显式转换。

 qrWriter.Write("text");

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

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