ProportionalSlice.cs 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. namespace Olympus
  4. {
  5. // Nine-slice corners always receive one uniform scale. Capsule caps follow the
  6. // control's height; rectangular panels retain a fixed corner size in UI units.
  7. [ExecuteAlways, RequireComponent(typeof(Image))]
  8. public sealed class ProportionalSlice : MonoBehaviour
  9. {
  10. public bool capsule;
  11. public float cornerSize = 18;
  12. Image target;
  13. void OnEnable() { Apply(); }
  14. void LateUpdate() { Apply(); }
  15. public void Apply()
  16. {
  17. if (!target) target = GetComponent<Image>();
  18. if (!target.sprite || target.type != Image.Type.Sliced) return;
  19. Vector4 b = target.sprite.border;
  20. if (b == Vector4.zero) return;
  21. var r = target.rectTransform.rect;
  22. float wanted = capsule ? r.height * .48f : Mathf.Min(cornerSize, Mathf.Min(r.width, r.height) * .42f);
  23. float source = Mathf.Max(b.y, b.w);
  24. if (wanted <= 0 || source <= 0) return;
  25. float multiplier = source / (target.pixelsPerUnit * wanted);
  26. if (Mathf.Abs(target.pixelsPerUnitMultiplier - multiplier) > .0001f)
  27. target.pixelsPerUnitMultiplier = multiplier;
  28. }
  29. }
  30. }