Rectangle.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using UnityEngine;
  3. namespace MPUIKIT {
  4. /// <summary>
  5. /// Basic Rectangle shape with the same width and height of the rect-transform
  6. /// </summary>
  7. [Serializable]
  8. public struct Rectangle : IMPUIComponent{
  9. [SerializeField] private Vector4 m_CornerRadius;
  10. #if UNITY_EDITOR
  11. [SerializeField] private bool m_UniformCornerRadius;
  12. #endif
  13. /// <summary>
  14. /// <para>Radius of the four corners. Counter-Clockwise from bottom-left</para>
  15. /// <para>x => bottom-left, y => bottom-right</para>
  16. /// <para>z => top-right, w => top-left</para>
  17. /// </summary>
  18. public Vector4 CornerRadius {
  19. get => m_CornerRadius;
  20. set {
  21. m_CornerRadius = Vector4.Max(value, Vector4.zero);
  22. if (ShouldModifySharedMat) {
  23. SharedMat.SetVector(SpRectangleCornerRadius, m_CornerRadius);
  24. }
  25. OnComponentSettingsChanged?.Invoke(this, EventArgs.Empty);
  26. }
  27. }
  28. public Material SharedMat { get; set; }
  29. public bool ShouldModifySharedMat { get; set; }
  30. public RectTransform RectTransform { get; set; }
  31. private static readonly int SpRectangleCornerRadius = Shader.PropertyToID("_RectangleCornerRadius");
  32. public void Init(Material sharedMat, Material renderMat, RectTransform rectTransform) {
  33. SharedMat = sharedMat;
  34. ShouldModifySharedMat = sharedMat == renderMat;
  35. RectTransform = rectTransform;
  36. }
  37. public event EventHandler OnComponentSettingsChanged;
  38. public void OnValidate() {
  39. CornerRadius = m_CornerRadius;
  40. }
  41. public void InitValuesFromMaterial(ref Material material) {
  42. m_CornerRadius = material.GetVector(SpRectangleCornerRadius);
  43. }
  44. public void ModifyMaterial(ref Material material, params object[] otherProperties)
  45. {
  46. Vector4 cornerRadius = FixRadius(m_CornerRadius);
  47. material.SetVector(SpRectangleCornerRadius, cornerRadius);
  48. }
  49. private Vector4 FixRadius(Vector4 radius)
  50. {
  51. Rect rect = RectTransform.rect;
  52. radius = Vector4.Max(radius, Vector4.zero);
  53. radius = Vector4.Min(radius, Vector4.one * Mathf.Min(rect.width, rect.height));
  54. float scaleFactor =
  55. Mathf.Min (
  56. Mathf.Min (
  57. Mathf.Min (
  58. Mathf.Min (
  59. rect.width / (radius.x + radius.y),
  60. rect.width / (radius.z + radius.w)),
  61. rect.height / (radius.x + radius.w)),
  62. rect.height / (radius.z + radius.y)),
  63. 1f);
  64. return radius * scaleFactor;
  65. }
  66. }
  67. }