Skip to content

Instantly share code, notes, and snippets.

@petersvp
Last active February 20, 2024 06:31
Show Gist options
  • Save petersvp/b22049e4260bea500122683199e90296 to your computer and use it in GitHub Desktop.
Save petersvp/b22049e4260bea500122683199e90296 to your computer and use it in GitHub Desktop.
A Layout Element controller to be added on an image within a Layout Group that can solve the height-for-width problem
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteAlways]
public class ImagePreferredSizeScaler : MonoBehaviour, ILayoutElement
{
Image image;
public float scale = 1;
[NaNField] public float width = float.NaN;
[NaNField] public float height = float.NaN;
public int LayoutPriority = 1;
private void OnEnable()
{
image = GetComponent<Image>();
UpdateLayout();
}
private void OnValidate()
{
UpdateLayout();
}
private void UpdateLayout()
{
LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent.GetComponent<RectTransform>());
}
void Update()
{
UpdateLayout();
}
public float minWidth => image.minWidth;
public float preferredWidth { get; set; }
public float flexibleWidth => image.flexibleWidth;
public float minHeight => image.minHeight;
public float preferredHeight { get; set; }
public float flexibleHeight => image.flexibleHeight;
public int layoutPriority => LayoutPriority;
public void CalculateLayoutInputHorizontal()
{
if(float.IsNaN(width) && !float.IsNaN(height))
{
float ratio = height / image.sprite.rect.height;
preferredWidth = image.sprite.rect.width * ratio;
preferredHeight = height;
}
}
public void CalculateLayoutInputVertical()
{
if (!float.IsNaN(width) && float.IsNaN(height))
{
float ratio = width / image.sprite.rect.width;
preferredWidth = width;
preferredHeight = image.sprite.rect.height * ratio;
}
else if(float.IsNaN(width) && float.IsNaN(height))
{
preferredWidth = image.sprite.rect.width * scale;
preferredHeight = image.sprite.rect.height * scale;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment