unity 通过http链接获取图片资源,并给到UI上

通过网络链接加载图片作为image贴图
完整代码

using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class LoadTexture : MonoBehaviour
{
    [Header("图片地址")]
    [SerializeField]   
    private string url = "https://img-blog.csdnimg.cn/20200114151229684.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAyMzMyOA==,size_16,color_FFFFFF,t_70";
    
    // Use this for initialization
    void Start()
    {
        StartCoroutine(DownSprite());

    }

    IEnumerator DownSprite()
    {
        UnityWebRequest wr = new UnityWebRequest(url);
        DownloadHandlerTexture texD1 = new DownloadHandlerTexture(true);
        wr.downloadHandler = texD1;
        yield return wr.SendWebRequest();
        int width = 1920;
        int high = 1080;
        if (!wr.isNetworkError)
        {
            Texture2D tex = new Texture2D(width, high);
            tex = texD1.texture;
            //保存本地          
            Byte[] bytes = tex.EncodeToPNG();
            File.WriteAllBytes(Application.dataPath + "/02.png", bytes);
             
            Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
            transform.GetComponent<Image>().sprite = sprite;
        }
    }

    private void OnApplicationQuit()
    {
        StopAllCoroutines();
    }
}

该脚本挂在image身上运行即可

成功
在这里插入图片描述

原文链接:https://blog.csdn.net/weixin_42540271/article/details/95337041

posted @   哒哒哒~~~  阅读(636)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示