image - 如何将类型 'UnityEngine.Texture2D' 转换为 'UnityEngine.Sprite?

标签 image unity3d sprite texture2d

您好,我尝试在图像中转换我的 Texture 2D(我不能使用原始图像,因为分辨率与手机不匹配)但问题是图像没有 Texture 元素。如何在Image.Sprite中转换UnityEngine.Texture2D。

//Image Profile
protected Texture2D pickedImage;
public Texture2D myTexture2D;
public RawImage getRawImageProfile;
public RawImage getRawImageArrayProfile;

public Image getRawImageProfile2;
public Image getRawImageArrayProfile2;

 public void PickImageFromGallery(int maxSize = 256)
{
    NativeGallery.GetImageFromGallery((path) => 
    {
        if( path != null )
        {
            byte[] imageBytes = File.ReadAllBytes(path);
            pickedImage = null;
            pickedImage = new Texture2D(2, 2);
            pickedImage.LoadImage(imageBytes);
            getRawImageProfile.texture = pickedImage;
            getRawImageArrayProfile.texture = pickedImage;

            getRawImageProfile2.sprite = pickedImage; //ERROR CONVERT SPRITE
            //getRawImageArrayProfile2.texture = pickedImage;
        }

    }, maxSize: maxSize);

    byte[] myBytes;
    myBytes = pickedImage.EncodeToPNG();
    enc = Convert.ToBase64String(myBytes);       
}

最佳答案

Sprite.Create 完全符合您的要求。

来自Unity docs在 Sprite.Create 上:

Sprite.Create creates a new Sprite which can be used in game applications. A texture needs to be loaded and assigned to Create in order to control how the new Sprite will look.

在代码中:

public Texture2D myTexture2D; // The texture you want to convert to a sprite
Sprite mySprite; // The sprite you're gonna save to
Image myImage; // The image on which the sprite is gonna be displayed

public void FooBar()
{
    mySprite = Sprite.Create(myTexture2D, new Rect(0.0f, 0.0f, myTexture2D.width, myTexture2D.height), new Vector2(0.5f, 0.5f), 100.0f);
    myImage.sprite = mySprite; // apply the new sprite to the image

}

在上面的示例中,我们从 myTexture2D 中获取图像数据,并创建一个与原始 texture2D 大小相同的 new Rect,其轴心点在中心,每单位使用 100 像素。然后我们将新制作的 Sprite 应用到图像。

关于image - 如何将类型 'UnityEngine.Texture2D' 转换为 'UnityEngine.Sprite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676894/

相关文章:

android - 恒定且可能不准确的帧率

css sprites - 悬停图像未正确加载

c# - 用于 concat 的 FFmpeg 管道输入

python - 我如何使pygame中的对象旋转

android - 可变屏幕分辨率 Sprite 不缩放统一

javascript - 鼠标悬停时更改图像源,然后鼠标移开时恢复图像

html - 无法固定 flexbox 盒子的宽度

java - 如何从网站上抓取全尺寸图像?

html - 将图像放置在 div 旁边(聊天气泡)

c# - 创建具有常量唯一 ID 的可编写脚本的对象