본문 바로가기
Unity3D/Unity & C#

Unity & C# ~ 이미지 파일을 로드하여 스프라이트로 만들기 (Image file Load to Sprite)

by 캬캬백곰 2023. 3. 14.
728x90

- 저장된 이미지 경로를 가지고 이미지를 로드하여 스프라이트로 형 변환을 한 후, 유니티 image ui에 넣기

using System.IO;
using UnityEngine;
using UnityEngine.UI;

public Image image;		// unity ui image
public string filePath;		// image file path
public Vector2 imageSize;	// image size x : width, y : height

public void LoadImage()
{
    byte[] byteTexture = File.ReadAllBytes(filePath);	// 파일 불러오기
    Texture2D texture2d = new Texture2D((int)imageSize.x, (int)imageSize.y);
    texture2d.LoadImage(byteTexture);
    
    Rect rect = new Rect(0, 0, texture2d.width, texture2d.height);
    Sprite sprite = Sprite.Create(texture2d, rect, new Vector2(0.5f, 0.5f));	// texture, rect. pivot
    image.sprite = sprite;
}
728x90
반응형