くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

【チラ裏】外部ファイルを読み込んでごにょごにょする(Unity C#)

チラ裏。本当のメモです。あしからず

UnityでAndroidを開発している時の備忘録。

外部ストレージにおいてあるPNGファイルをロードして、Textureにつっこんで、表示したかった。。。 が、高解像度のファイルの場合、OpenGLのエラーで落ちてうまくいかない。。。

public void setImage(string path) {
        Debug.Log("path:" + path);
        string url = "file://" + path;
        StartCoroutine(GetWww(url));
    }

    IEnumerator GetWww(string url) {
        //TODO can not show large photo because OpenGL error on Android
        Debug.Log("###### START Coroutine");

        Debug.Log("url:" + url);
        WWW www = new WWW(url);
        yield return www;

        Texture2D texture = www.texture;
        ResizeTexture(texture);

        SpriteRenderer spr = currentChara.GetComponent<SpriteRenderer>();
        Rect cRect = spr.sprite.rect;
        Rect rect = new Rect(cRect.x, cRect.y, texture.width, texture.height);

        Sprite sprite = Sprite.Create(texture, rect,new Vector2(0.5f,0.5f), 100.0f);
        spr.sprite = sprite;


        float maxWidth = Screen.width;
        float maxHeight = Screen.height;
        float s = 1;

        if (rect.width < rect.height) {//height
            if (rect.height < maxHeight) {
                s = maxHeight / rect.height;
            }
        } else {//width
            if (rect.width < maxWidth) {
                s = maxWidth / rect.width;
            }
        }

        currentChara.transform.localScale = new Vector3(s, s, 0);
        Debug.Log("###### END Coroutine");
    }

    void ResizeTexture(Texture2D tex) {
        float maxWidth = Screen.width * 0.8f;
        float maxHeight = Screen.height * 0.6f;
        float s = 1;
        Debug.Log("texture: " + tex.width + ", " + tex.height);
        Debug.Log("max: " + maxWidth + ", " + maxHeight);

        if (tex.width < tex.height) {//height
            if (tex.height > maxHeight) {
                s = maxHeight / tex.height;
            }
        } else {//width
            if (tex.width > maxWidth) {
                s = maxWidth / tex.width;
            }
        }

        if(s != 1) {
            int newWidth = (int) (tex.width * s);
            int newHeight = (int) (tex.height * s);
            // tex.Resize(newWidth, newHeight, TextureFormat.ETC2_RGBA8, false);
            tex.Resize(newWidth, newHeight);
            // tex.anisoLevel = 5;
            tex.Apply();

            Debug.Log("new texture: s-" + s + " :" + newWidth + ", " + newHeight);
        } else {
            Debug.Log("new texture: s-" + s);
        }
    }