Skip to content

Instantly share code, notes, and snippets.

@tklee1975
Last active October 30, 2021 10:22
Show Gist options
  • Select an option

  • Save tklee1975/1e3bead4b9f0731cb9e5e17ff68e748b to your computer and use it in GitHub Desktop.

Select an option

Save tklee1975/1e3bead4b9f0731cb9e5e17ff68e748b to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(RawImage))]
[ExecuteInEditMode]
public class AspectFitRawImage : MonoBehaviour
{
protected RawImage m_rawImage;
protected Vector2 m_rectSize = Vector2.one;
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
GetRectSize(); // Get the view rect size
m_rawImage = GetComponent<RawImage>(); // Get the image
DoAspectFit();
}
protected void GetRectSize() {
RectTransform tf = transform as RectTransform;
m_rectSize = tf.sizeDelta;
if(m_rectSize.x == 0 || m_rectSize.y == 0) {
m_rectSize = (transform.parent as RectTransform).sizeDelta;
}
if(m_rectSize.x <= 0 || m_rectSize.y <= 0) { // Fail back logic
m_rectSize = Vector2.one;
}
}
protected virtual void DoAspectFit() {
if(m_rawImage == null) {
Debug.Log("AspectFitRawImage: m_rawImage is null");
return;
}
Texture texture = m_rawImage.texture;
if(texture == null) {
Debug.Log("AspectFitRawImage: texture is null");
return;
}
float w = texture.width;
float h = texture.height;
if(w == h) {
m_rawImage.uvRect = new Rect(0, 0, 1, 1);
return; // nothing to do
}
float textureRatio = w/h;
float viewRatio = m_rectSize.x/m_rectSize.y;
// ken: some debug value
// Debug.Log("rectSize=" + m_rectSize);
// Debug.Log("w=" + w + " h=" + h);
// Debug.Log("textureRatio=" + textureRatio + " viewRatio=" + viewRatio);
if(viewRatio == textureRatio) {
if(m_rawImage != null) {
m_rawImage.uvRect = new Rect(0, 0, 1, 1);
}
}
if(viewRatio > textureRatio) { // middle potion of the image
float potionRatio = textureRatio / viewRatio; // (diff - 1) * textureRatio;
float offset = (1 - potionRatio) * 0.5f;
m_rawImage.uvRect = new Rect(0, offset, 1, potionRatio);
} else {
float potionRatio = viewRatio / textureRatio; // (diff - 1) * textureRatio;
float offset = (1 - potionRatio) * 0.5f;
m_rawImage.uvRect = new Rect(offset, 0, potionRatio, 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment