С помощью этого кода можно загрузить картинку из файла в объект с Sprite Renderer.
Проблема в том, что картинка отображается буквально точкой на экране - 1 или 2 пикселя.
Как это исправить?
Код скрипта
Синтаксис:
Используется csharp
public class LoadImage : MonoBehaviour
{
string filePath;// it is as "D:/Unity/Photo-Voodoo/FotoTest/img1.jpg"
public byte[] fileData; // load data inside a byte array 0x89,0x50,0x4E,0x47,0x0D...
void Start ()
{
var _image = GameObject.Find("Image200x200onCanvas");
var _spriteRenderer = _image.GetComponent<SpriteRenderer>();
filePath = @"C:\TEMP\test.jpg"; // Путь к картинке.
fileData = File.ReadAllBytes(filePath); // 1.read the bytes array
Texture2D tex = new Texture2D(2, 2); // 2.create a texture named tex
tex.LoadImage(fileData); // 3.load inside tx the bytes and use the correct image size
Rect rec = new Rect(0, 0, tex.width, tex.height); // 4.create a rect using the textute dimensions
Sprite spriteToUse = Sprite.Create(tex,rec,new Vector2(0.5f,0.5f),100); //5. convert the texture in sprite
_spriteRenderer.sprite = spriteToUse; //6.load the sprite used by UI Image
}
}
{
string filePath;// it is as "D:/Unity/Photo-Voodoo/FotoTest/img1.jpg"
public byte[] fileData; // load data inside a byte array 0x89,0x50,0x4E,0x47,0x0D...
void Start ()
{
var _image = GameObject.Find("Image200x200onCanvas");
var _spriteRenderer = _image.GetComponent<SpriteRenderer>();
filePath = @"C:\TEMP\test.jpg"; // Путь к картинке.
fileData = File.ReadAllBytes(filePath); // 1.read the bytes array
Texture2D tex = new Texture2D(2, 2); // 2.create a texture named tex
tex.LoadImage(fileData); // 3.load inside tx the bytes and use the correct image size
Rect rec = new Rect(0, 0, tex.width, tex.height); // 4.create a rect using the textute dimensions
Sprite spriteToUse = Sprite.Create(tex,rec,new Vector2(0.5f,0.5f),100); //5. convert the texture in sprite
_spriteRenderer.sprite = spriteToUse; //6.load the sprite used by UI Image
}
}
Сцена
Результат