Changing Pivot of rotated RectTransform makes the Object jump to an incorrect Position

I’m trying to change the Pivot of a RectTransform during runtime, which works perfectly when the Object is not rotated. Unfortunatly the Object has to be rotateable and that’s when a problem arises, when changing the Pivot of the rotated Object it jumps to an incorrect Position.

Can someone point me in the right direction?

Code I’m using:

public void changePivot(Vector2 pivot)
{
     Vector2 deltaPivot = pivot - RectTransform.pivot;

     float deltaX = deltaPivot.x * RectTransform.sizeDelta.x * RectTransform.localScale.x;
     float deltaY = deltaPivot.y * RectTransform.sizeDelta.y * RectTransform.localScale.y;

     Vector3 deltaPosition = new Vector3(deltaX, deltaY);

     RectTransform.pivot = pivot;
     RectTransform.localPosition += deltaPosition;
}

A colleague has found a solution for the problem I was having. Here’s the solution we’re currently using.

private void changePivot(Vector2 pivot)
{
      Vector2 deltaPivot = RectTransform.pivot - pivot;
           
      float deltaX = deltaPivot.x * RectTransform.sizeDelta.x * RectTransform.localScale.x;
      float deltaY = deltaPivot.y * RectTransform.sizeDelta.y * RectTransform.localScale.y;

      float rot = RectTransform.rotation.eulerAngles.z * Mathf.PI / 180;
      Vector3 deltaPosition = new Vector3(Mathf.Cos(rot) * deltaX - Mathf.Sin(rot) * deltaY, Mathf.Sin(rot) * deltaX + Mathf.Cos(rot) * deltaY);

       RectTransform.pivot = pivot;
       RectTransform.localPosition -= deltaPosition;
}