Unity 浏览本地图片并加载

在开发过程中,经常会有在软件中浏览本地文件的需求,今天就在Unity中实现一下浏览本地图片并加载的小功能。
功能预览:
Unity 浏览本地图片并加载_第1张图片
其实实现起来很方便。注释中都有代码,只需要两个代码,一个是调用系统的窗口,一个是加载图片

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

/// 
/// 调用系统的窗口,数据接收类
/// 
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName   
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

public class WindowDll
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
    public static bool GetOpenFileName1([In, Out] OpenFileName ofn)
    {
        return GetOpenFileName(ofn);
    }
}
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Reflection;
using UnityEngine.UI;

public class LoadImage : MonoBehaviour
{

    public Image image;

    public Texture buttonTexture;


    // Update is called once per frame
    void Update()
    {

    }

    void OnGUI()
    {
        //设置按钮文字的大小,颜色,背景等
        GUIStyle fontStyle = new GUIStyle();
        fontStyle.alignment = TextAnchor.MiddleCenter;
        fontStyle.fontSize = 50;
        fontStyle.normal.textColor = Color.white;
        fontStyle.normal.background = (Texture2D)buttonTexture;


        if (GUI.Button(new Rect(10, 10, 300, 100), "Open",fontStyle))
        {
            OpenFileName ofn = new OpenFileName();
            ofn.structSize = Marshal.SizeOf(ofn);
            ofn.filter = "图片文件(*.jpg*.png)\0*.jpg;*.png";
            ofn.file = new string(new char[256]);
            ofn.maxFile = ofn.file.Length;
            ofn.fileTitle = new string(new char[64]);
            ofn.maxFileTitle = ofn.fileTitle.Length;
            //默认路径
            string path = Application.streamingAssetsPath;
            path = path.Replace('/', '\\');
            //默认路径
            //ofn.initialDir = "G:\\wenshuxin\\test\\HuntingGame_Test\\Assets\\StreamingAssets";
            ofn.initialDir = path;           
            ofn.title = "Open Project";
            ofn.defExt = "JPG";//显示文件的类型
            //注意 一下项目不一定要全选 但是0x00000008项不要缺少
            ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR
            //点击Windows窗口时开始加载选中的图片
            if (WindowDll.GetOpenFileName(ofn))
            {
                Debug.Log("Selected file with full path: " + ofn.file);
                StartCoroutine(Load(ofn.file));
            }
        }
    }

   
    /// 
    /// 加载本地图片
    /// 
    /// 本地文件路径
    /// 
    IEnumerator Load(string path)
    {   //计算加载用时    
        double startTime = (double)Time.time; 
        

        WWW www = new WWW("file:///" + path);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;
            //更多操作...
            //直接将选择图保存
            byte[] bytes = texture.EncodeToJPG();
            //测试地址
            //string filename = @"G:\wenshuxin\BackGround\6.jpg";
            System.IO.File.WriteAllBytes(path, bytes);
            //根据获取的Texture创建一个sprite
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            //将sprite显示在图片上
            image.sprite = sprite;
            //图片设置为原始尺寸
            image.SetNativeSize();


            //计算加载用时
            startTime = (double)Time.time - startTime;
            Debug.Log("WWW加载用时:" + startTime);
        }
    }
   
}

你可能感兴趣的:(Unity,开发)