/// <summary>
/// 网络地址加载图片
/// </summary>
/// <param name="url">地址</param>
/// <param name="raw">图片显示位置</param>
public void loadImage(string url,RawImage raw)
{
string imageName = GetImageName(url);
string myUrl = FilePath + imageName + ".png";
isImgExist = File.Exists(url);
if (isImgExist)
{
StartCoroutine(startLoad(myUrl, imageName, raw));
}
else
{
if (IsValidUrl(url))
{
StartCoroutine(startLoad(url, imageName, raw));
}
else
{
Debug.Log("网址不对!");
raw.texture = sprite.texture;
}
}
}
/// <summary>
/// 加载图片
/// </summary>
/// <param name="url">图片地址</param>
/// <param name="name">唯一不重复变量</param>
/// <param name="raw">图片显示位置</param>
/// <returns></returns>
IEnumerator startLoad(string url, string name, RawImage raw)
{
//加载图片
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(url))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError)
{
//Debug.Log(www.error);
raw.texture = sprite.texture;
}
else
{
/*这里把贴图转换的过程放到了后台线程来完成,
并且相比于直接脚本加载图片做了优化,减少了内存分配*/
Debug.Log(www);
Texture2D tx = DownloadHandlerTexture.GetContent(www);
raw.texture = tx;
//raw.GetComponent<RectTransform>().sizeDelta = new Vector2(imageWidth, (tx.height * 1.0f / tx.width) * imageWidth);
//图片保存到本地
if (!isImgExist)
{
Byte[] bytes = tx.EncodeToPNG();
File.WriteAllBytes(FilePath + "\\" + name + ".png", bytes);
}
}
}
}
/// <summary>
/// 判断网址对不对
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool IsValidUrl(string url)
{
string pattern = @"^(http|https):\/\/([a-zA-Z0-9]+[-\.]?)+(:[0-9]{1,5})?(\/.*)?$";
return System.Text.RegularExpressions.Regex.Match(url, pattern).Success;
}
/// <summary>
/// 从网址中获取名图片名字
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string GetImageName(string url)
{
if (!IsValidUrl(url)) return "";
string str;
int lastSlashIndex = url.LastIndexOf('/');
if (lastSlashIndex != -1)
{
str = url.Substring(lastSlashIndex + 1); // 通过Substring()函数删除最后一个'/'之前的部分
}
else
{
Debug.Log("地址有问题!");
str = "";
}
int lastSuffixIndex = str.LastIndexOf('.');//删除后缀
str = str.Remove(lastSuffixIndex, str.Length - lastSuffixIndex);
return str;
}