Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. static class CanvasExtensions {
  2. public static Vector2 SizeToParent(this RawImage image, float padding = 0) {
  3. var parent = image.transform.parent.GetComponentInParent<RectTransform>();
  4. var imageTransform = image.GetComponent<RectTransform>();
  5. if (!parent) { return imageTransform.sizeDelta; } //if we don't have a parent, just return our current width;
  6. padding = 1 - padding;
  7. float w = 0, h = 0;
  8. float ratio = image.texture.width / (float)image.texture.height;
  9. var bounds = new Rect(0, 0, parent.rect.width, parent.rect.height);
  10. if (Mathf.RoundToInt(imageTransform.eulerAngles.z) % 180 == 90) {
  11. //Invert the bounds if the image is rotated
  12. bounds.size = new Vector2(bounds.height, bounds.width);
  13. }
  14. //Size by height first
  15. h = bounds.height * padding;
  16. w = h * ratio;
  17. if (w > bounds.width * padding) { //If it doesn't fit, fallback to width;
  18. w = bounds.width * padding;
  19. h = w / ratio;
  20. }
  21. imageTransform.sizeDelta = new Vector2(w, h);
  22. return imageTransform.sizeDelta;
  23. }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement