Changing an image size cancels its anchoring?

I have a 2D game in which I have a simple UI image of a rectangle that is anchored to the middle right.

In my script, I’m changing the image’s size like so:

RectTransform objectRectTransform_bar_bg = bar_bg.GetComponent< RectTransform >();
objectRectTransform_bar_bg.sizeDelta = new Vector2(Screen.width, Screen.height / 2.35f);

When I run my game, and the image’s width changes, it seems like the anchor does’nt work any more and the image shifts to the left instead of remaining locked to the right side. When I change the image’s width using the editor (not via script), it works and the image stays locked on the right side.

What can cause this? Am I doing something wrong?

There’s a function for this btw: RectTransform.SetSizeWithCurrentAnchors

var newSize = new Vector2(Screen.width, Screen.height / 2.35f);

objectRectTransform_bar_bg.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, newSize.x);
objectRectTransform_bar_bg.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, newSize.y);