【发布时间】:2018-05-12 10:58:27
【问题描述】:
我想下载我已上传到服务器的多张图片,并在我的场景中的画廊或幻灯片中显示。我已经完成了下面的代码来下载图像,但我只能显示一张图像。如何显示从服务器下载的多张图片?
public void DownloadtheFiles()
{
List <string> photolist = ES2.LoadList<string>("myPhotos.txt");
for (int i = 0; i < photolist.Count; i++) {
new GetUploadedRequest()
.SetUploadId(photolist[i])
.Send((response) =>
{
StartCoroutine(DownloadImages(response.Url));
} );
}
}
public IEnumerator DownloadImages(string downloadUrl)
{
var www = new WWW(downloadUrl);
yield return www;
downloadedImages = new Texture2D(200, 200);
www.LoadImageIntoTexture(downloadedImages);
imageLoaded.texture = downloadedImages as Texture;
}
更新 1:使用下面的代码,我展示了我希望如何展示它们,但它从文件夹路径获取图像,我需要展示我从服务器下载的图像。如何集成此代码以使用下载的图像制作幻灯片?
public class ImageLoader : MonoBehaviour
{
[SerializeField]
[Tooltip("The folder where images will be loaded from")]
private string imagePath;
[SerializeField]
[Tooltip("The panel where new images will be added as children")]
private RectTransform content;
private List<Texture2D> textures;
private void Start()
{
Application.runInBackground = true;
StartCoroutine(LoadImages());
}
public IEnumerator LoadImages()
{
textures = new List<Texture2D>();
DirectoryInfo di = new DirectoryInfo(imagePath);
var files = di.GetFiles("*.png");
foreach (var file in files)
{
Debug.Log(file.FullName);
yield return LoadTextureAsync(file.FullName, AddLoadedTextureToCollection);
}
CreateImages();
}
private void AddLoadedTextureToCollection(Texture2D texture)
{
textures.Add(texture);
}
private void CreateImages()
{
foreach(var texture in textures)
{
GameObject imageObject = new GameObject("Image");
imageObject.transform.SetParent(content);
imageObject.AddComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
}
public IEnumerator LoadTextureAsync(string originalFileName, Action<Texture2D> result)
{
string fileToLoad = GetCleanFileName(originalFileName);
Debug.Log("Loading Image from path: " + fileToLoad);
WWW www = new WWW(fileToLoad);
yield return www;
Texture2D loadedTexture = new Texture2D(1, 1);
www.LoadImageIntoTexture(loadedTexture);
result(loadedTexture);
}
private static string GetCleanFileName(string originalFileName)
{
string fileToLoad = originalFileName.Replace('\\', '/');
if (fileToLoad.StartsWith("http") == false)
{
fileToLoad = string.Format("file://{0}", fileToLoad);
}
return fileToLoad;
}
}
更新 2:我创建了一个 ScrollView 和 HorizonatalLayoutGroup,并应用了更新 1 的 ImageLoader.cs。我在文件夹中添加了 4 个图像,这些是层次结构和结果的屏幕截图:
它作为测试工作正常,但图像的来源是我电脑中的一个文件夹,我想下载服务器的图像。我该怎么做?
【问题讨论】:
-
你想在哪里显示图像?用户界面? 2D 还是 3D 对象?
-
我想在 UI 中显示所有图片
-
嗨@Programmer 有什么办法解决这个问题吗?
-
什么 UI 组件?也许它在 Inspector 选项卡中的屏幕截图?如果您尝试下载多个图像,那么您将需要多个该 UI 组件。你有多少?抱歉,这还不足以帮助您。
-
@Programmer 现在可以正常工作了!!!非常感谢您对我的耐心等待!!!!