- Home /
screen position of element in layout
I have a horizontal layout that has 3 children , i want to get the actual pixel screen position of the second child, the grid, i need this position because i am taking a screenshot of the second child, i can successfully get the width and height. see screenshot
What i tried, i need the opposite of RectTransformUtility.ScreenPointToLocalPointInRectangle
public Rect GetGridSize() {
Rect rect = gridTransform.rect;
//float scaleX = Screen.width / canvasScaler.referenceResolution.x;
bool landscape = Screen.width > Screen.height;
//float width = rect.width * scaleX;
CanvasScale = new Vector2((float) Screen.width / canvasScaler.referenceResolution.x, (float)Screen.height / canvasScaler.referenceResolution.y);
float scaleY = ((landscape) ? CanvasScale.y : CanvasScale.x);
float scaleX = ((landscape) ? CanvasScale.x : CanvasScale.y);
float height = Mathf.Round(rect.height * scaleY);
float layoutLeft = gridTransform.parent.GetComponent<RectTransform> ().offsetMin.x;
return new Rect((layoutLeft + gridTransform.offsetMin.x) * scaleX, Mathf.Round(25f * scaleY), height, height);
}
Answer by dappledore · Nov 02, 2016 at 04:59 AM
I answered my own question, i had to convert to world coordinates first and then to screen point. check revised method below. This question helped
public Rect GetGridSize() {
Rect rect = gridTransform.rect;
Vector3[] corners = new Vector3[4];
gridTransform.GetWorldCorners(corners);
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint (Camera.main,corners[0]);
print ("grid x " + screenPoint.x);
//float scaleX = Screen.width / canvasScaler.referenceResolution.x;
bool landscape = Screen.width > Screen.height;
//float width = rect.width * scaleX;
CanvasScale = new Vector2((float) Screen.width / canvasScaler.referenceResolution.x, (float)Screen.height / canvasScaler.referenceResolution.y);
float scaleY = ((landscape) ? CanvasScale.y : CanvasScale.x);
float scaleX = ((landscape) ? CanvasScale.x : CanvasScale.y);
float height = Mathf.Round(rect.height * scaleY);
//float layoutLeft = gridTransform.parent.GetComponent<RectTransform> ().offsetMin.x;
return new Rect(screenPoint.x, Mathf.Round(25f * scaleY), height, height);
}
Your answer
Follow this Question
Related Questions
UI RectTransform Position && Screen Resolution 2 Answers
pixel in unit in unity3d and have a full screen texture 1 Answer
Touch.position, Touch.deltaPosition, Screen.width, Screen.Height 1 Answer
Set Rect Transform Screen Position 0 Answers
this code doesnt work when the buttons anchor are not same(custom anchor) 0 Answers