| | 1 | | using UnityEngine; |
| | 2 | | using UnityEngine.UI; |
| | 3 | |
|
| | 4 | | /// <summary> |
| | 5 | | /// RawImage that resize itself to fill it parent while preserving it texture's aspect ratio. |
| | 6 | | /// |
| | 7 | | /// Caution: This component doesn't work with UI atlases! |
| | 8 | | /// </summary> |
| | 9 | | public class RawImageFillParent : RawImage |
| | 10 | | { |
| | 11 | | new public Texture texture |
| | 12 | | { |
| | 13 | | set |
| | 14 | | { |
| 15 | 15 | | base.texture = value; |
| | 16 | |
|
| 15 | 17 | | if (value != null) |
| | 18 | | { |
| 13 | 19 | | ResizeFillParent(); |
| | 20 | | } |
| 15 | 21 | | } |
| 0 | 22 | | get { return base.texture; } |
| | 23 | | } |
| | 24 | |
|
| | 25 | | protected override void Awake() |
| | 26 | | { |
| 106 | 27 | | base.Awake(); |
| 106 | 28 | | if (texture != null) |
| | 29 | | { |
| 48 | 30 | | ResizeFillParent(); |
| | 31 | | } |
| 106 | 32 | | } |
| | 33 | |
|
| | 34 | | void ResizeFillParent() |
| | 35 | | { |
| 61 | 36 | | if (transform.parent == null) |
| | 37 | | { |
| 0 | 38 | | return; |
| | 39 | | } |
| | 40 | |
|
| 61 | 41 | | RectTransform parent = transform.parent as RectTransform; |
| | 42 | |
|
| | 43 | | float h, w; |
| 61 | 44 | | h = parent.rect.height; |
| 61 | 45 | | w = h * (base.texture.width / (float) base.texture.height); |
| | 46 | |
|
| 61 | 47 | | if ((parent.rect.width - w) > 0) |
| | 48 | | { |
| 22 | 49 | | w = parent.rect.width; |
| 22 | 50 | | h = w * (base.texture.height / (float) base.texture.width); |
| | 51 | | } |
| | 52 | |
|
| 61 | 53 | | rectTransform.sizeDelta = new Vector2(w, h); |
| 61 | 54 | | } |
| | 55 | | } |