您的位置:首页 > 移动开发 > Unity3D

Unity 加载本地图片文件

2016-09-23 16:23 465 查看
此篇文章主要记录如何在Unity PC环境下加载本地图片

在讲解如何加载本地文件之前,先解决在编译过程可能遇到的一个错误提示:

Unhandled Exception: System.TypeLoadException: Could not load type 'System.ComponentModel.CancelEventHandler' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

………………………………


如下所示:



解决方法如下:

因为 Mono 平台支持 .net 3.5,所以只能使用 NET20 的 System.Windows.Forms.dll导致了此问题。



解决办法:

Unity 菜单 Edit->Project Settings->Player, 在 Player 设置里选择 Api Comatibility Level 从 .NET 2.0 Subset 改为 .NET 2.0。

using UnityEngine;
using System.Collections;
using System.Windows.Forms;
using System.IO;
public class UI_0923 : MonoBehaviour {

// Use this for initialization
void Start () {
}

string TexPath;
void OnGUI()
{
if(GUI.Button(new Rect(0,0,50,150),"加载本地图片"))
{
OpenFileDialog od = new OpenFileDialog();
od.Title = "请选择图片";
od.Multiselect = false;
od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";

if (od.ShowDialog() == DialogResult.OK)
TexPath = od.FileName;

if (!File.Exists(TexPath))
Debug.Log("加载失败");

//WWW方式加载图片
//StartCoroutine(WWW_Tex("file://" + TexPath));

//FileStream方式加载图片
FileStreamLoadTexture();
}

//WWW方式加载图片——显示
if (wwwTexture != null)
{
GUI.DrawTexture(new Rect(0, 0, wwwTexture.width, wwwTexture.height), wwwTexture);
}

//FileStream方式加载图片——显示
if (OriginalTex != null)
{
GUI.DrawTexture(new Rect(0, 0, OriginalTex.width, OriginalTex.height), OriginalTex);
}
}

/// <summary>
/// WWW加载图片
/// </summary>
Texture2D wwwTexture;
IEnumerator WWW_Tex(string url)
{
WWW www = new WWW(url);
yield return www;
if (www.isDone && www.error == null)
{
wwwTexture = www.texture;
}
}

/// <summary>
/// 文件流加载图片
/// </summary>
Texture2D OriginalTex;
void FileStreamLoadTexture()
{
//通过路径加载本地图片
FileStream fs = new FileStream(TexPath, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
OriginalTex = new Texture2D(2, 2);
var iSLoad = OriginalTex.LoadImage(buffer);
OriginalTex.Apply();
if (!iSLoad)
{
Debug.Log("Texture存在但生成Texture失败");
}
}
}


运行效果如下:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity