【问题标题】:Converting a texture to a sprite将纹理转换为精灵
【发布时间】:2018-08-20 20:52:48
【问题描述】:

我有一个纹理用作屏幕截图。 当我将纹理保存为 png 文件时,它看起来很完美,但我也想在屏幕上显示捕获的图像。所以我将纹理转换为精灵,但由于某种原因,最终结果精灵只是我在屏幕上拥有的另一个 UI 图像的随机图像,而不是我保存到正确的 png 文件的纹理。

这是我的代码:

        var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
        Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
        WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
        tex.ReadPixels(rex, rdPXX, rdPXY);
        tex.Apply();

        // Encode texture into PNG
        var bytes = tex.EncodeToPNG();
        Sprite sprite = new Sprite();
        sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
        image.GetComponent<Image>().overrideSprite = sprite;
        Destroy(tex);

【问题讨论】:

    标签: c# unity3d textures sprite


    【解决方案1】:

    不要破坏纹理。 Sprite 总是需要一个纹理参考。 Sprite 对象仅保留有关纹理的元数据,例如枢轴或 UV(精灵图集中的位置和大小)

    【讨论】:

      【解决方案2】:

      只需使用带参数的 Sprite.Create() 直接创建精灵。 Unity 现在是 Create() 的默认构造函数。也不要破坏纹理。

      试试这个,

              var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
              Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
              WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
              tex.ReadPixels(rex, rdPXX, rdPXY);
              tex.Apply();
      
              // Encode texture into PNG
              var bytes = tex.EncodeToPNG();
              Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
              image.GetComponent<Image>().overrideSprite = sprite;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多