#nullable enable using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [Serializable] public class ObjectPresentation { public string name; public RawImage image; public TMPro.TextMeshProUGUI text; public GameObject root; public ObjectPresentation( string name, RawImage image, TMPro.TextMeshProUGUI text, GameObject root ) { this.name = name; this.image = image; this.text = text; this.root = root; } } public class ObjectZoomPanel : MonoBehaviour { public List objectPresentations; public Dictionary objectPresentationDict; void BuildDic() { objectPresentationDict = new Dictionary(); foreach (ObjectPresentation objectPresentation in objectPresentations) { objectPresentationDict[objectPresentation.name] = objectPresentation; } } private void SetImageDim(RawImage image, Texture texture) { image.texture = texture; // Get the RectTransforms RectTransform rectTransform = image.GetComponent(); RectTransform parentRectTransform = rectTransform.parent as RectTransform; // Get the size of the parent RectTransform float parentWidth = parentRectTransform.rect.width; float parentHeight = parentRectTransform.rect.height; // Calculate the aspect ratio of the image float imageAspectRatio = (float)texture.width / texture.height; float parentAspectRatio = parentWidth / parentHeight; float newWidth, newHeight; // Fit the image to the parent while maintaining aspect ratio if (imageAspectRatio > parentAspectRatio) { // Image is wider relative to its height than the parent newWidth = parentWidth; newHeight = parentWidth / imageAspectRatio; } else { // Image is taller relative to its width than the parent newWidth = parentHeight * imageAspectRatio; newHeight = parentHeight; } // fit new image size to parent size // Set the size of the RectTransform to the new size rectTransform.sizeDelta = new Vector2(newWidth, newHeight); // Center the RectTransform in the parent rectTransform.anchoredPosition = Vector2.zero; } public void SetImage(ClickableZoom clickableZoom) { if (objectPresentationDict == null || objectPresentationDict.Count == 0) BuildDic(); ObjectPresentation objectPresentation = objectPresentationDict["horizontal"]; if (clickableZoom.text.Split("\n").Length > 2 || !clickableZoom.Horizontal) { objectPresentation = objectPresentationDict["vertical"]; } foreach (ObjectPresentation op in objectPresentations) { op.root.SetActive(op == objectPresentation); } SetImageDim(objectPresentation.image, clickableZoom.fullImage); objectPresentation.text.text = clickableZoom.text; } }