需求:Unity开发PC端,使用资源管理器加载本地资源。
1.调用Win32打开资源管理器对话框
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileDlg
{
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 OpenFileDialog
{
[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern bool GetOpenFileName([In, Out] OpenFileDlg ofd);
}
2.通过对话框获取选择文件的路径
public void BtnTest()
{
OpenFileDlg pth = new OpenFileDlg();
pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
pth.filter = "文件(*.jpg )\0*.jpg";//筛选文件类型
pth.initialDir = "Wen";
pth.file = new string(new char[256]);
pth.maxFile = pth.file.Length;
pth.fileTitle = new string(new char[64]);
pth.maxFileTitle = pth.fileTitle.Length;
pth.initialDir = Application.streamingAssetsPath.Replace('/', '\\');
pth.title = "上传素材";
pth.defExt = "JPG";//显示文件类型
pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
if (OpenFileDialog.GetOpenFileName(pth))
{
string filepath = pth.file;//选择的文件路径;
DirectoryInfo i = new DirectoryInfo(filepath);
//上级目录
string path = i.Parent.FullName;//返回文件的上级目录
Debug.Log(path);//文件目录父目录
Debug.Log(i.FullName);//文件路径全
StartCoroutine(LoadIamge(i.FullName));
}
3.如果需要直接加载图片到UGUI上,可以协程进行加载。
IEnumerator LoadIamge(string path)
{ //计算加载用时
double startTime = Time.time;
WWW www = new WWW("file:///" + path);
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
//获取Texture
Texture2D texture = www.texture;
//根据获取的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();
loadSprite = sprite;
//计算加载用时
startTime = Time.time - startTime;
Debug.Log("WWW加载用时:" + startTime);
}
}