如何将类型'UnityEngine.Texture2D'转换为'UnityEngine.Sprite? [英] How convert type 'UnityEngine.Texture2D' to 'UnityEngine.Sprite?

查看:878
本文介绍了如何将类型'UnityEngine.Texture2D'转换为'UnityEngine.Sprite?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Image中转换我的Texture 2D(并且我不能使用Raw Image,因为分辨率在手机中不匹配),但是问题是Image没有Texture元素.如何在Image.Sprite中转换UnityEngine.Texture2D.

Hi i try to convert my Texture 2D in Image (and i cant use a Raw Image because the resolution dont match in phones) but the problem is that Image does not have the Texture element. how Convert UnityEngine.Texture2D in Image.Sprite.

//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完全满足您的需求.

在Sprite.Create上的 Unity文档中:

From the Unity docs on Sprite.Create:

Sprite.Create创建一个可以在游戏应用程序中使用的新Sprite.需要加载纹理并将其分配给创建",以控制新Sprite的外观.

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个像素.然后,我们将新制作的精灵应用于图像.

In the above example we take the image data from myTexture2D, and create a new Rect that is of the same size as the original texture2D, with its pivot point in the center, using 100 pixels per unit. We then apply the newly made sprite to the image.

这篇关于如何将类型'UnityEngine.Texture2D'转换为'UnityEngine.Sprite?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆