在游戏中微信登录一般要使用微信用户头像
lua代码
--设置玩家头像
function PlayerModel.SetUserInfo()
//this.Head为头像url,function 是去远程下载回调,远程下载内容是下载写入到本地,返回本地图片路径
Util.DownloadImage(this.Head,function (filepash,isdone)
//开启从本地下载图片协成
coroutine.start(this.loadImage,filepash)
end);
end
function PlayerModel.loadImage(filepash)
//读取的时候一定要加file://前缀,jar:前缀不用加
local www = WWW("file://"..filepash)
Yield(www)
if www.error ~= nil then
print("lua<<设置头像--加载本地图片失败");
print(www.error);
else
MainPagePanel.HeadIcon:GetComponent("Image").sprite = Util.CreateSprite(www.texture);
end
www:Dispose();
end
public static void DownloadImage(int uid,string sourceUrl, LuaFunction callback)
{
if (!ValidateURI(sourceUrl))
{
callback.Call(GetImage(), false);
return;
}
string localFileName = sourceUrl.Substring(sourceUrl.LastIndexOf("/") + 1);
if (!localFileName.Contains(".png"))
{
localFileName = uid + localFileName + ".png";
}
string localPath = DataPath + "usericon/" + localFileName;
if (IsFileExist(localPath))
{
callback.Call(GetImage(localPath), true);
return;
}
WWWRequest request = new WWWRequest(sourceUrl);
WWWHelper.Instance.AddWWWTask(request, new WWWHelper.WWWBeginDownLoad(delegate ()
{
}),
new WWWHelper.WWWFinishDownLoad(delegate (WWW www)
{
CreatFile(www.bytes, localPath);
// CreatFile(www.bytes,localFileName);
callback.Call(GetImage(localPath), true);
}),
new WWWHelper.WWWDownLoadError(delegate (WWW www, WWWRequest requestBase)
{
Debug.Log("WWWDownLoadError");
}));
}
/// <summary>
///
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static bool ValidateURI(string uri)
{
Regex validipregex = new Regex(@"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?");
return (uri != "" && validipregex.IsMatch(uri.Trim())) ? true : false;
}
/// <summary>
///
/// </summary>
/// <returns>The image.</returns>
/// <param name="path">Path</param>
public static string GetImage(string path = null)
{
if (path == null)
{
path = "file://" + Application.dataPath + "/Resources/Image/defaultIcon.png";
}
return path;
}
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool IsFileExist(string fullPath)
{
FileInfo fileInfo = new FileInfo(fullPath);
return fileInfo.Exists;
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="file"></param>
public static void CreatFile(byte[] bytes, string savePath)
{
FileInfo file = new FileInfo(savePath);
Stream stream;
if (!file.Directory.Exists)
{
file.Directory.Create();
}
stream = file.Create();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
stream.Dispose();
}
public static Sprite CreateSprite(Texture2D texture)
{
return Sprite.Create(texture, new Rect(0,0,texture.width,texture.height),Vector2.zero);
}
}