Skip to content

Commit

Permalink
feat: Angle Gradient gradation supports RectTransform pivot
Browse files Browse the repository at this point in the history
  • Loading branch information
mob-sakai committed Jan 7, 2025
1 parent 88ab733 commit 39dc7f1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Packages/src/Runtime/UIEffectContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,7 @@ private void ApplyGradation(List<UIVertex> verts, Rect rect, Matrix4x4 m, bool c
GradientUtil.DoRadialGradient(verts, a, b, offset, scale, rect, m, 12);
break;
case GradationMode.Angle:
rect = GradientUtil.RotateRectAsNormalized(rect, rot);
m = Matrix4x4.Rotate(Quaternion.Euler(0, 0, rot)) * m;
GradientUtil.DoHorizontalGradient(verts, a, b, offset, scale, rect, m);
break;
Expand Down Expand Up @@ -517,6 +518,7 @@ private void ApplyGradation(List<UIVertex> verts, Rect rect, Matrix4x4 m, bool c
GradientUtil.GetKeyTimes(grad, _keyTimes);
}

rect = GradientUtil.RotateRectAsNormalized(rect, rot);
m = Matrix4x4.Rotate(Quaternion.Euler(0, 0, rot)) * m;
if (canModifyShape)
{
Expand Down
36 changes: 36 additions & 0 deletions Packages/src/Runtime/Utilities/GradientUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,5 +339,41 @@ static bool Contains(List<float> list, float v)
return false;
}
}

public static Rect RotateRectAsNormalized(Rect rect, float rot)
{
var rad = -rot * Mathf.Deg2Rad;
var cos = Mathf.Cos(rad);
var sin = Mathf.Sin(rad);
var dir = new Vector2(cos, sin);
var center = rect.center;

if (Mathf.Abs(dir.x) < 0.0001f)
{
rect.width = rect.height;
}
else if (Mathf.Abs(dir.y) < 0.0001f)
{
rect.height = rect.width;
}
else
{
var d0 = GetPointToLineDistance(new Vector2(rect.xMin, rect.yMax), center, dir, out var p0);
var d1 = GetPointToLineDistance(new Vector2(rect.xMin, rect.yMin), center, dir, out var p1);
var closest = d0 < d1 ? p0 : p1;
rect.width = rect.height = Vector2.Distance(center, closest) * 2;
}

rect.center = new Vector2(Vector2.Dot(center, dir), 0);
return rect;
}

private static float GetPointToLineDistance(Vector2 point, Vector2 origin, Vector2 dir, out Vector2 closest)
{
var dirNormalized = dir.normalized;
var time = Vector2.Dot(point - origin, dirNormalized);
closest = origin + time * dirNormalized;
return Vector2.Distance(point, closest);
}
}
}

0 comments on commit 39dc7f1

Please sign in to comment.