根据图片路径动态更改Image的显示

using System.Collections;

using System.Collections.Generic;

using System.IO;

using UnityEngine;

using UnityEngine.UI;

[RequireComponent(typeof(Image))]

public class ImageLoader : MonoBehaviour

{

    [SerializeField]

    private string _relativePath;

    private Texture2D _texture;

    private Image _img;

    public string RelativePath

    {

        get { return _relativePath; }

        set {

            _relativePath = value;

            ReLoadImage();

        }

    }

    private void Awake()

    {

        _img = GetComponent<Image>();

    }

    void Start()

    {

        ReLoadImage();

    }

    public void ReLoadImage()

    {

        if (!string.IsNullOrEmpty(_relativePath))

        {

            var data = ReadPNG(_relativePath);

            if (data != null)

            {

                _texture = new Texture2D(1, 1);

                _texture.LoadImage(data);

                _img.sprite = Sprite.Create(_texture, new Rect(0, 0, _texture.width, _texture.height), new Vector2(0, 0));

                return;

            }

        }

        _img.sprite = null;

    }

    private byte[] ReadPNG(string path)

    {

        string fullPath = path;

        if (!string.IsNullOrEmpty(fullPath))

        {

            FileStream fileStream = new FileStream(fullPath, FileMode.Open, System.IO.FileAccess.Read);

            fileStream.Seek(0, SeekOrigin.Begin);

            byte[] binary = new byte[fileStream.Length]; 

            fileStream.Read(binary, 0, (int)fileStream.Length);

            fileStream.Close();

            fileStream.Dispose();

            fileStream = null;

            return binary;

        }

        return null;

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容