How convert type 'UnityEngine.Texture2D' to 'UnityEngine.Sprite?

北战南征 提交于 2020-06-29 03:48:16

问题


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

回答1:


Sprite.Create does exactly what you're looking for.

From the Unity docs on 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.

In code:

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

}

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.



来源:https://stackoverflow.com/questions/56676894/how-convert-type-unityengine-texture2d-to-unityengine-sprite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!