您当前的位置: 首页 >  unity

unity工具人

暂无认证

  • 3浏览

    0关注

    205博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

unity工具人 发布时间:2020-05-18 14:59:51 ,浏览量:3

通过网络链接加载图片作为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().sprite = sprite;
        }
    }

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

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

成功 在这里插入图片描述

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

关注
打赏
1656671177
查看更多评论
立即登录/注册

微信扫码登录

0.0446s