Hi,
I was in need of a solution to place a UITexture inside a Clipped Panel, so that it would fit keeping its aspect ratio.
The UIStretch did not provide a valid solution, as it is based on fixed values specified in the editor, and the Texture can change at runtime.
So, I wrote a simple script, based off of UIStretch, which will correctly fit the UITexture into the Clipped Panel, and respect its aspect ratio.
Im sure it could be improved, but it works fine for me, so I thought I would share it

using UnityEngine;
[ExecuteInEditMode]
[RequireComponent
(typeof(UITexture
))] public class UITextureAspectRatio : MonoBehaviour
{
/// <summary>
/// Panel used to determine the container's bounds. Overwrites the widget-based anchoring if the value was specified.
/// </summary>
public UIPanel panelContainer = null;
private UITexture mUITexture;
private Rect mRect;
private Transform mTrans;
void Awake() {
mTrans = transform;
}
void Start() {
mUITexture = GetComponent<UITexture>();
Update();
}
void Update() {
if (panelContainer != null)
{
if (panelContainer.clipping == UIDrawCall.Clipping.None)
{
// Panel has no clipping -- just use the screen's dimensions
mRect.xMin = -Screen.width * 0.5f;
mRect.yMin = -Screen.height * 0.5f;
mRect.xMax = -mRect.xMin;
mRect.yMax = -mRect.yMin;
}
else
{
// Panel has clipping -- use it as the rect
Vector4 pos = panelContainer.clipRange;
mRect.x = pos.x - (pos.z * 0.5f);
mRect.y = pos.y - (pos.w * 0.5f);
mRect.width = pos.z;
mRect.height = pos.w;
}
}
Vector3 localScale = mTrans.localScale;
float rectWidth = mRect.width;
float rectHeight = mRect.height;
Texture tex = mUITexture.mainTexture;
Rect uvRect = mUITexture.uvRect;
float texWidth = tex.width * uvRect.width;
float texHeight = tex.height * uvRect.height;
float screenRatio = rectWidth / rectHeight;
float imageRatio = texWidth / texHeight;
if (imageRatio > screenRatio)
{
// Fit horizontally
float scale = rectWidth / texWidth;
localScale.x = rectWidth;
localScale.y = texHeight * scale;
}
else
{
// Fit vertically
float scale = rectHeight / texHeight;
localScale.x = texWidth * scale;
localScale.y = rectHeight;
}
if (mTrans.localScale != localScale) mTrans.localScale = localScale;
}
}