0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AspectRatioFilterのaspectRatioを動的に変更する

Posted at

はじめに

AspectRatioFilterは縦横比を維持しながら画面に隙間なくImageを表示するためのコンポーネントですが、表示するImageの縦横比を前もって設定する必要があります。なので縦横比が違う画像を動的にImageに設定するなどの場合は当然そのままでは縦横比が合わなくなります。僕自身ここで詰まってしまったので解決方法を書こうと思いました。

結論

Sprite.texture2d.width,Sprite.texture2d.heightを使います。

Sprite.texture2d.width,Sprite.texture2d.heightはint型なので縦横比を求める際は(float)をつける必要があります。

実装例

SourceData.LoadBackGround[]: AssetReference[]

Test
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using UnityEngine.AddressableAssets;
using UnityEngine.UI;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace Test
{
    public static class LoadManager 
    {
        private static AsyncOperationHandle<Sprite> handle;
        public static async UniTask LoadActionAsync(SourceData data, Image image, GameObject obj, AspectRatioFitter filter)
        {
            int num = Random.Range(0, data.LoadBackground.Length);
            handle = Addressables.LoadAssetAsync<Sprite>(data.LoadBackground[num]);
            await handle.Task;

            if (handle.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded)
            {
                image.sprite = handle.Result;
                var texture2d = image.sprite.texture;
                float aspect_ratio = (float)texture2d.width / (float)texture2d.height;
                filter.aspectRatio = aspect_ratio;
                obj.SetActive(true);
            }
            else
            {
                Debug.LogError($"Failed to load Json: {handle.OperationException.Message}");
            }

            await UniTask.Delay(System.TimeSpan.FromSeconds(2));
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?