-2

我正在尝试使用 ZXing.Net 生成 QR 码,起初我遇到了.Save()由于错误 CS1061 而无法正常工作的问题。所以,我放弃了这个想法,然后我尝试保存.Write()为图像,然后统一渲染,但 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();
    }

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

4

1 回答 1

1

首先

找不到类型或命名空间名称“图像”

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

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以设置所需的像素尺寸,如本博客所示:

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

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

于 2019-11-03T17:09:34.557 回答