batteryDiagnosis/Assets/Scripts/TestWebImage.cs

82 lines
2.1 KiB
C#

using UnityEngine;
using UnityEngine.UI;
public class TestWebImage : MonoBehaviour
{
public WebImageLoader webImageLoader;
public RawImage testImage;
public Button testButton;
public Text statusText;
void Start()
{
if (testButton != null)
{
testButton.onClick.AddListener(TestLoadImage);
}
}
void TestLoadImage()
{
if (webImageLoader != null)
{
// 设置要加载的图片URL
string imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/120px-HTML5_logo_and_wordmark.svg.png";
// 设置回调
webImageLoader.imageDisplay = testImage;
webImageLoader.OnLoadSuccess = OnLoadSuccess;
webImageLoader.OnLoadFailed = OnLoadFailed;
webImageLoader.OnProgressChanged = OnProgressChanged;
// 开始加载
webImageLoader.LoadImageFromUrl(imageUrl, 10); // 10秒超时
if (statusText != null)
{
statusText.text = "开始加载图片...";
}
}
}
void OnLoadSuccess(Texture2D texture)
{
if (statusText != null)
{
statusText.text = $"加载成功! 尺寸: {texture.width}x{texture.height}";
}
Debug.Log("测试图片加载成功!");
}
void OnLoadFailed(string error)
{
if (statusText != null)
{
statusText.text = $"加载失败: {error}";
}
Debug.LogError($"测试图片加载失败: {error}");
}
void OnProgressChanged(float progress)
{
if (statusText != null)
{
statusText.text = $"加载中... {(int)(progress * 100)}%";
}
}
void OnDestroy()
{
if (webImageLoader != null)
{
webImageLoader.OnLoadSuccess = null;
webImageLoader.OnLoadFailed = null;
webImageLoader.OnProgressChanged = null;
}
if (testButton != null)
{
testButton.onClick.RemoveListener(TestLoadImage);
}
}
}