Skip to content

Commit 2f63adf

Browse files
committed
feat: Angle Gradient gradation supports RectTransform pivot
1 parent 7cb8325 commit 2f63adf

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Packages/src/Runtime/UIEffectContext.cs

+2
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,7 @@ private void ApplyGradation(List<UIVertex> verts, Rect rect, Matrix4x4 m, bool c
462462
GradientUtil.DoRadialGradient(verts, a, b, offset, scale, rect, m, 12);
463463
break;
464464
case GradationMode.Angle:
465+
rect = GradientUtil.RotateRectAsNormalized(rect, rot);
465466
m = Matrix4x4.Rotate(Quaternion.Euler(0, 0, rot)) * m;
466467
GradientUtil.DoHorizontalGradient(verts, a, b, offset, scale, rect, m);
467468
break;
@@ -517,6 +518,7 @@ private void ApplyGradation(List<UIVertex> verts, Rect rect, Matrix4x4 m, bool c
517518
GradientUtil.GetKeyTimes(grad, _keyTimes);
518519
}
519520

521+
rect = GradientUtil.RotateRectAsNormalized(rect, rot);
520522
m = Matrix4x4.Rotate(Quaternion.Euler(0, 0, rot)) * m;
521523
if (canModifyShape)
522524
{

Packages/src/Runtime/Utilities/GradientUtil.cs

+36
Original file line numberDiff line numberDiff line change
@@ -339,5 +339,41 @@ static bool Contains(List<float> list, float v)
339339
return false;
340340
}
341341
}
342+
343+
public static Rect RotateRectAsNormalized(Rect rect, float rot)
344+
{
345+
var rad = -rot * Mathf.Deg2Rad;
346+
var cos = Mathf.Cos(rad);
347+
var sin = Mathf.Sin(rad);
348+
var dir = new Vector2(cos, sin);
349+
var center = rect.center;
350+
351+
if (Mathf.Abs(dir.x) < 0.0001f)
352+
{
353+
rect.width = rect.height;
354+
}
355+
else if (Mathf.Abs(dir.y) < 0.0001f)
356+
{
357+
rect.height = rect.width;
358+
}
359+
else
360+
{
361+
var d0 = GetPointToLineDistance(new Vector2(rect.xMin, rect.yMax), center, dir, out var p0);
362+
var d1 = GetPointToLineDistance(new Vector2(rect.xMin, rect.yMin), center, dir, out var p1);
363+
var closest = d0 < d1 ? p0 : p1;
364+
rect.width = rect.height = Vector2.Distance(center, closest) * 2;
365+
}
366+
367+
rect.center = new Vector2(Vector2.Dot(center, dir), 0);
368+
return rect;
369+
}
370+
371+
private static float GetPointToLineDistance(Vector2 point, Vector2 origin, Vector2 dir, out Vector2 closest)
372+
{
373+
var dirNormalized = dir.normalized;
374+
var time = Vector2.Dot(point - origin, dirNormalized);
375+
closest = origin + time * dirNormalized;
376+
return Vector2.Distance(point, closest);
377+
}
342378
}
343379
}

0 commit comments

Comments
 (0)