開発入門 > Unity > Gameobjectのテクスチャをアスペクト比正しく貼り付ける

Gameobjectのテクスチャをアスペクト比正しく貼り付ける

Unityで貼り付ける元画像の縦横比と、貼り付け先の縦横比が違った場合、引き伸ばされて画像が表示されてしまいます。

下記のように、アスペクト比が異なる場合は、画像がいっぱいに表示されるように調整して貼り付けます。

NekoImage

        /// <summary>
        /// //指定したウェブ画像を読み込んでゲームオブジェクトのテクスチャとして表示(適切に表示サイズを調整)
        /// 読み込み画像が最大で表示されるように表示部分が自動調整されます
        /// </summary>
        /// <param name="url"></param>
        /// <param name="gObj"></param>
        /// <returns></returns>
        public static IEnumerator<WWW> attacheWebImageToGameobject_appropriately(string url, GameObject gObj)
        {
            WWW texturewww = new WWW(url);
            yield return texturewww;
            gObj.GetComponent<Renderer>().material.mainTexture = texturewww.texture;

            float Obj_x = gObj.transform.lossyScale.x;
            float Obj_y = gObj.transform.lossyScale.y;
            float Img_x = (float)texturewww.texture.width;
            float Img_y = (float)texturewww.texture.height;

            float aspectRatio_Obj = Obj_x / Obj_y;
            float aspectRatio_Img = Img_x/Img_y;

            if (aspectRatio_Img> aspectRatio_Obj)
            {
                //イメージサイズのほうが横に長い場合
                gObj.GetComponent<Renderer>().material.SetTextureScale("_MainTex", new Vector2(aspectRatio_Obj / aspectRatio_Img, 1f));
                gObj.GetComponent<Renderer>().material.SetTextureOffset("_MainTex", new Vector2(   (Img_x-(Obj_x*Img_y/Obj_y))/(2*Img_x)         , 1f));
            }
            else
            {
                //イメージサイズのほうが縦に長い場合
                gObj.GetComponent<Renderer>().material.SetTextureScale("_MainTex", new Vector2(1f,  aspectRatio_Img/ aspectRatio_Obj));
                gObj.GetComponent<Renderer>().material.SetTextureOffset("_MainTex", new Vector2(1f,  (Img_y-Obj_y*Img_x/Obj_x)/(2*Img_y)          ));
            }
        }

 

 

 

カテゴリー: Unity

HOME / Coporate Site/ Careers

© Copyright 2018 STYLY..