Reputation: 133
I have UI elements (image, etc). Canvas attached to camera.
There is a RectTransform
, but how to convert this data to screen or world coordinates and get center point of this image?
Tried RectTransform.GetWorldCorners
but it returns zero vectors.
Upvotes: 13
Views: 27162
Reputation: 1042
Following Huacanacha's guidance,
Vector2 _centerPosition = _rectTransform.TransformPoint(_rectTransform.rect.center);
will give you the WorldCoordinate of the center of the image.
Upvotes: 0
Reputation: 13146
You can work with GetWorldCorners
but only when using a child that has real dimensions. I got reasonable values for a child of a world space canvas.
Upvotes: 2
Reputation: 1161
yourRectTransform.rect.center
for the centre point in local space.
yourRectTransform.TransformPoint
to convert to world space.
It is odd that RectTransform.GetWorldCorners
doesn't work as stated. Per one of the other answers you need to call after Awake (so layout can occur).
Upvotes: 19
Reputation: 71
I found that both GetWorldCorners and TransformPoint only work on Start(), not on Awake(), as if we'll have to wait for the content to be resized
Vector3 min = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.min);
Vector3 max = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.max);
elementToResize.transform.localScale = new Vector3(Mathf.Abs(min.x - max.x) , Mathf.Abs(min.y - max.y), 1f);
elementToResize.transform.position = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.center);
Upvotes: 4