Unity3d中(加载(内部、外部))显示图片(sprite、texture2d)

介绍:在这片中将逐渐添加开发中遇到的各种加载图片的方法、情况

 

一、使用文件流(FileStream)从指定文件夹中读取图片

   

    /// <summary>
    /// 从外部指定文件中加载图片
    /// </summary>
    /// <returns></returns>
    private Texture2D LoadTextureByIO()
    {
        FileStream fs = new FileStream(@"D:\" + "图片文件名的全程(包含后缀名)比如  1.png", FileMode.Open, FileAccess.Read);
        fs.Seek(0, SeekOrigin.Begin);//游标的操作,可有可无
        byte[] bytes = new byte[fs.Length];//生命字节,用来存储读取到的图片字节
        try
        {
            fs.Read(bytes, 0, bytes.Length);//开始读取,这里最好用trycatch语句,防止读取失败报错

        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
        fs.Close();//切记关闭

        int width = 2048;//图片的宽(这里两个参数可以提到方法参数中)
        int height = 2048;//图片的高(这里说个题外话,pico相关的开发,这里不能大于4k×4k不然会显示异常,当时开发pico的时候应为这个问题找了大半天原因,因为美术给的图是6000*3600,导致出现切几张图后就黑屏了。。。
        Texture2D texture = new Texture2D(width, height);
        if (texture.LoadImage(bytes))
        {
            print("图片加载完毕 ");
            return texture;//将生成的texture2d返回,到这里就得到了外部的图片,可以使用了

        }
        else
        {
            print("图片尚未加载");
            return null;
        }
    }

经过上边的方法获取到了外部的图片,得到的是Texture2d,如果目的是需要sprite,则调用下边的方法即可

    /// <summary>
    /// 将Texture2d转换为Sprite
    /// </summary>
    /// <param name="tex">参数是texture2d纹理</param>
    /// <returns></returns>
    private Sprite TextureToSprite(Texture2D tex)
    {
        Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        return sprite;
    }

还可以将所需的外部图片存放到一个List集合中,实现预览效果

此效果源码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.UI;

public class TestOpenFile : MonoBehaviour {

    private Button btn;//部落按钮
    private Button nextBtn;//下一张按钮
    private Image image;//用来显示图片

    private Sprite sprite;//粗放sprite类型的图片

    private List<Sprite> spriteList = new List<Sprite>();//存放sprite的list(存放很多张)
    private string[] files;//存放指定路径下的所有图片的路径

    private int index = 0;

    private void Awake()
    {
        btn = GameObject.Find("btn").GetComponent<Button>();
        nextBtn = GameObject.Find("Next").GetComponent<Button>();
        image = GameObject.Find("Image").GetComponent<Image>();
        btn.onClick.AddListener(BtnOnClicked);
        nextBtn.onClick.AddListener(NextOnClicked);
        GetSpriteList();

    }

    /// <summary>
    /// 显示部落图片的按钮点击事件
    /// </summary>
    private void BtnOnClicked()
    {
        sprite = TextureToSprite(LoadTextureByIO());
        image.sprite = sprite;
    }

    /// <summary>
    /// 切图按钮点击事件
    /// </summary>
    private void NextOnClicked()
    {
        if (index >= files.Length)
        {
            index = 0;
        }
        image.sprite = spriteList[index];
        index++;
    }

    /// <summary>
    /// 获取指定路径下的所有图片(sprite类型
    /// </summary>
    private void GetSpriteList()
    {
        files = Directory.GetFiles(@"D:\zzw\My\Picture\壁纸");
        foreach (var item in files)
        {
            Debug.Log(item);
        }
        for (int i = 0; i < files.Length; i++)
        {
            spriteList.Add(TextureToSprite(LoadTextureByIO(files[i])));
        }
    }

    /// <summary>
    /// 从外部指定文件中加载图片
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <returns></returns>
    private Texture2D LoadTextureByIO(string path)
    {
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
        fs.Seek(0, SeekOrigin.Begin);//游标的操作,可有可无
        byte[] bytes = new byte[fs.Length];//生命字节,用来存储读取到的图片字节
        try
        {
            fs.Read(bytes, 0, bytes.Length);//开始读取,这里最好用trycatch语句,防止读取失败报错

        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
        fs.Close();//切记关闭

        int width = 2048;//图片的宽(这里两个参数可以提到方法参数中)
        int height = 2048;//图片的高(这里说个题外话,pico相关的开发,这里不能大于4k×4k不然会显示异常,当时开发pico的时候应为这个问题找了大半天原因,因为美术给的图是6000*3600,导致出现切几张图后就黑屏了。。。
        Texture2D texture = new Texture2D(width, height);
        if (texture.LoadImage(bytes))
        {
            print("图片加载完毕 ");
            return texture;//将生成的texture2d返回,到这里就得到了外部的图片,可以使用了

        }
        else
        {
            print("图片尚未加载");
            return null;
        }
    }

    /// <summary>
    /// 这个同上,区别在于无参,写死路径
    /// </summary>
    /// <returns></returns>
    private Texture2D LoadTextureByIO()
    {
        FileStream fs = new FileStream(@"D:\zzw\My\Picture\壁纸\部落.jpg", FileMode.Open, FileAccess.Read);
        fs.Seek(0, SeekOrigin.Begin);//游标的操作,可有可无
        byte[] bytes = new byte[fs.Length];//生命字节,用来存储读取到的图片字节
        try
        {
            fs.Read(bytes, 0, bytes.Length);//开始读取,这里最好用trycatch语句,防止读取失败报错

        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
        fs.Close();//切记关闭

        int width = 2048;//图片的宽(这里两个参数可以提到方法参数中)
        int height = 2048;//图片的高(这里说个题外话,pico相关的开发,这里不能大于4k×4k不然会显示异常,当时开发pico的时候应为这个问题找了大半天原因,因为美术给的图是6000*3600,导致出现切几张图后就黑屏了。。。
        Texture2D texture = new Texture2D(width, height);
        if (texture.LoadImage(bytes))
        {
            print("图片加载完毕 ");
            return texture;//将生成的texture2d返回,到这里就得到了外部的图片,可以使用了

        }
        else
        {
            print("图片尚未加载");
            return null;
        }
    }


    /// <summary>
    /// 将Texture2d转换为Sprite
    /// </summary>
    /// <param name="tex">参数是texture2d纹理</param>
    /// <returns></returns>
    private Sprite TextureToSprite(Texture2D tex)
    {
        Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        return sprite;
    }
}
---------------------------------分割线-----------------------------------
以下为补充代码,需要替换,不能全部复制。加入上一张按钮功能,且运行后默认显示文件夹中的第一张图片
第一个方法为新增函数(自己声明并绑定下点击事件)
后两个方法直接吧上边的替换掉
/// <summary>
    /// 上一张按钮点击事件
    /// </summary>
    private void PreviousOnClicked()
    {
        index--;
        if (index < 0)
        {
            index = files.Length - 1;
        }
        image.sprite = spriteList[index];
    }

    /// <summary>
    /// 下一张按钮点击事件
    /// </summary>
    private void NextOnClicked()
    {
        index++;
        if (index >= files.Length)
        {
            index = 0;
        }
        image.sprite = spriteList[index];
    }

    /// <summary>
    /// 获取指定路径下的所有图片(sprite类型
    /// </summary>
    private void GetSpriteList()
    {
        files = Directory.GetFiles(@"D:\zzw\My\Picture\壁纸");
        foreach (var item in files)
        {
            Debug.Log(item);
        }
        for (int i = 0; i < files.Length; i++)
        {
            spriteList.Add(TextureToSprite(LoadTextureByIO(files[i])));
        }
        image.sprite = spriteList[index];
    }



 

未完待续。。。

2020-7-28

二、使用协程来加载外部图片。


public RawImage raw;//记得外部赋值下

private void Start()
    {

         StartCoroutine(LoadTexture(filePathTexture));//再Start中调用即可
    }

/// <summary>
/// 协程加载外部图片
/// </summary>
/// <param name="path">图片的路径</param>
/// <returns></returns>
IEnumerator LoadTexture(string path)
    {
        //WWW已经被弃用,如果要加载Texture则需要用到下边的方法
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
        yield return www.SendWebRequest();
        //image.texture = texd1;
        if (www != null && !m_Request.isError)//这一步代表图片读取完毕
        {
            raw.texture = DownloadHandlerTexture.GetContent(www);
            raw.SetNativeSize();//将读取到的Texture设置为原大小
        }
    }

/// <summary>
/// 协程加载外部图片
/// 方法功能和上边一模一样,但使用了using关键字
/// using 语句定义一个范围,在此范围的末尾将释放对象。提供可确保正确使用 IDisposable 对象的方便语法。注意使用前提:该对象必须继承了IDisposable接口,功能等同于try{}Finally{ }。
/// 建议使用此方法而不是上边那个
/// </summary>
/// <param name="path">图片的路径</param>
/// <returns></returns>
IEnumerator LoadTexture(string path)
    {
        using (UnityWebRequest m_Request = UnityWebRequestTexture.GetTexture(path))
        {
            yield return m_Request.SendWebRequest();
            if (m_Request == null || m_Request.isError)
            {
                Debug.Log("加载失败");
            }
            else
            {
                raw.texture = DownloadHandlerTexture.GetContent(m_Request);
                raw.SetNativeSize();//将读取到的Texture设置为原大小
            }
        }
    }

  • 11
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 24
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值