Performance: Anchoring and responsive UI
Anchoring affects how UI elements resize and reposition during screen size changes, impacting rendering and layout recalculations.
Jump into concepts and practice - no test required
RectTransform rt = GetComponent<RectTransform>(); rt.anchorMin = new Vector2(0.5f, 0.5f); rt.anchorMax = new Vector2(0.5f, 0.5f); rt.anchoredPosition = Vector2.zero; // center anchored rt.sizeDelta = new Vector2(200, 50); // size relative to anchors
RectTransform rt = GetComponent<RectTransform>(); rt.anchoredPosition = new Vector2(100, 100); // fixed position rt.sizeDelta = new Vector2(200, 50); // fixed size
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fixed position and size | High (many recalculations) | Multiple on resize | High due to layout shifts | [X] Bad |
| Relative anchoring with flexible positions | Low (minimal recalculations) | Single on resize | Low, stable visuals | [OK] Good |
rectTransform.anchorMin = new Vector2(0.5f, 0.5f); rectTransform.anchorMax = new Vector2(0.5f, 0.5f); rectTransform.anchoredPosition = new Vector2(100, 50);Where will the UI element appear relative to its parent?
rectTransform.anchorMin = new Vector2(1, 1); rectTransform.anchorMax = new Vector2(0, 0); rectTransform.anchoredPosition = new Vector2(0, 0);