Twitterのicon画像を取得して,動的にVR空間上に表示する

TwitterREST APIでタイムラインのユーザーのアイコンのurlを取得して変えていきます

 

成果物

こちらが今回の成果になります

 

 

f:id:ka1357amnbpdr:20190929164729p:plain

 

 

 実装内容

localにicon画像の保存

まずは,ローカルに画像を持っていて変更するようにしました!

(急にリクエスト送って,変更とか難しいから...)

f:id:ka1357amnbpdr:20190929160947p:plain

このように,4色の画像に変更できました

一応コードを載せます.(メモ代わり)

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

public class UserDetails : MonoBehaviour {
    private string imgURL;//アイコンのurlを入れる
    [SerializeFieldprivate Image image;//ボタンのアイコンの画像
    [SerializeFieldprivate Sprite testImage;
    public void SetImgURL(string url){
        imgURL = url;
    }
    // Use this for initialization
    void Start () {
        image.sprite = testImage;
    }
    
    // Update is called once per frame
    void Update () {
        
    }
}

f:id:ka1357amnbpdr:20190929161104p:plain

 

icon画像の取得

では,TwitterREST APIをつかってユーザーのicon画像を取得していきます

github.com

 

今回使っているTwityでiconの画像を取得しないといけないので,変数の確認します

using System;
   
  namespace Twity.DataModels.Core
  {
  [Serializable]
  public class TweetUser
  {
  public long id;
  public string id_str;
  public string name;
  public string screen_name;
  public string location;
  public string description;
  public string url;
  public bool verified;
   
  public string profile_text_color;
  public bool profile_user_background_image;
  public string profile_background_image_url;
  public string profile_background_image_url_https;
  public string profile_background_color;
  public string profile_banner_url;
  public bool profile_background_tile;
  public string profile_image_url;
   
  public int statuses_count;
  public int friends_count;
  public int followers_count;
  public int favourites_count;
  public bool following;
  public bool follow_request_sent;
  public int listed_count;
   
  public TweetObject status;
   
  }
  }

 

 この中に,profile_image_urlがあるので,これを使いたいと思います.

参考記事

www.hanachiru-blog.com

コード
IEnumerator Start()
    {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(imgURL);

        //画像を取得できるまで待つ
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            //取得した画像のテクスチャをRawImageのテクスチャに張り付ける
            texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
        }
    }

 

しかし,これでは表示できませんでした...

取得した画像はTexture2Dだったのです

ここで,textureからspriteに変更します.

 

kamisawa.net

今回はコードをコピペして...

    Sprite ConvertToSprite(Texture2D texture)
    {
        return Sprite.Create(texturenew Rect(00texture.widthtexture.height), Vector2.zero);
    }

 

これで,変換ができました.

 

あとは,アイコンのところにspriteに反映させます.

image.sprite = ConvertToSprite(texture);

これで,できました!!

 

ちょっと読み込む数を多くすると初めの読み込みに時間がかかるので,対策を考えないといけないみたいです...