はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【Unity】Aspect Ratio Fitterを使って画像のアスペクト比を一定にしながらサイズを変更する

はじめに

今回は画像のアスペクト比を一定にすることができるAspect Ratio Fitterコンポーネントについて紹介したいと思います。

f:id:hanaaaaaachiru:20210703181405p:plain
Aspect Ratio Fitterの有無

早速みていきましょう。

Aspect Ratio Fitter

Aspect Ratio Fitter は冒頭でも述べたように、アスペクト比(widthHeightの比率)を一定に強制的にする機能になります。

Aspect Ratio Fitter - Unity マニュアル

Aspect Ratio Fitterを利用するには、まずAspect Modeというアスペクト比率を維持するためにどのようにサイズ変更をするかを指定します。

Aspect Mode 意味
None アスペクト比率を無視します
Width Controls Height 高さは幅にもとづいて自動的に調整されます
Height Controls Width 幅は高さにもとづいて自動的に調整されます
Fit In Paren 幅、高さ、位置、アンカーは、アスペクト比率を維持しながら矩形が親矩形の内側に合うように自動的に調整されます。親矩形の内部には、この矩形で覆われていないスペースがある場合もあります。
Envelope Parent 幅、高さ、位置、アンカーは、アスペクト比率を維持しながら親矩形の全体を覆うよう自動的に調整されます。この矩形は親矩形よりも大きくなるかもしれません。

Aspect Ratio Fitter - Unity マニュアル

f:id:hanaaaaaachiru:20210703182015p:plain
Aspect Ratio Fitterコンポーネント


後はAspect Ratioによりアスペクト比を決定します。

名前 意味
Aspect Ratio 強制的に維持するアスペクト比率。この値は、幅を高さで割ったものです。

Width Controls Height

f:id:hanaaaaaachiru:20210703220037p:plain
Width Controls Heightのインスペクター

Width Controls Heightを設定すると、RectTransformHeightは設定できなくなります。

だとするとHeightはどう決定されるかと思うかもしれませんが、Height = Aspect Ratio * Widthにより決定されるようになるわけですね。

Height Controls Width

f:id:hanaaaaaachiru:20210703220257p:plain
Height Controls Width

Height Controls Widthを設定すると、RectTransformWidthは設定できなくなります。

Width Controls Heightとは逆に、Width = Aspect Ratio * Heightにより決定されます。

Fit In Parent

f:id:hanaaaaaachiru:20210703215200g:plain
Fit In ParentのAspect Ratioを変化させた様子

Fit In Parentは必ず親のサイズよりも小さく、高さか幅のどちらか一方が親と同じになります。

f:id:hanaaaaaachiru:20210703215643p:plain
Fit In Parentのインスペクター

またRectTransformPosition.XYWidth・Heightは操作できなくなります。

Envelope Parent

f:id:hanaaaaaachiru:20210703215123g:plain
Envelope ParentのAspect Ratioを変化させた様子

Envelope Parentは必ず親のサイズよりも大きく、高さか幅のどちらか一方が親と同じになります。

>

f:id:hanaaaaaachiru:20210703215844p:plain
Envelope Parent no
RectTransformのPosition.XYWidth・Heightは操作できなくなります。