| | 1 | | using UnityEngine; |
| | 2 | |
|
| | 3 | | public static class TextureHelpers |
| | 4 | | { |
| | 5 | | public static void EnsureTexture2DMaxSize(ref Texture2D texture, int maxTextureSize) |
| | 6 | | { |
| 0 | 7 | | if (texture == null) |
| 0 | 8 | | return; |
| | 9 | |
|
| 0 | 10 | | if (texture.width == 0 || texture.height == 0) |
| 0 | 11 | | return; |
| | 12 | |
|
| 0 | 13 | | if (Mathf.Max(texture.height, texture.width) <= maxTextureSize) |
| 0 | 14 | | return; |
| | 15 | |
|
| | 16 | | int w, h; |
| 0 | 17 | | if (texture.height > texture.width) |
| | 18 | | { |
| 0 | 19 | | h = maxTextureSize; |
| 0 | 20 | | w = (int) ((texture.width / (float) texture.height) * h); |
| 0 | 21 | | } |
| | 22 | | else |
| | 23 | | { |
| 0 | 24 | | w = maxTextureSize; |
| 0 | 25 | | h = (int) ((texture.height / (float) texture.width) * w); |
| | 26 | | } |
| | 27 | |
|
| 0 | 28 | | var newTexture = Resize(texture, w, h); |
| 0 | 29 | | var oldTexture = texture; |
| 0 | 30 | | texture = newTexture; |
| 0 | 31 | | Object.Destroy(oldTexture); |
| 0 | 32 | | } |
| | 33 | |
|
| | 34 | | public static Texture2D Resize(Texture2D source, int newWidth, int newHeight) |
| | 35 | | { |
| 89 | 36 | | source.filterMode = FilterMode.Point; |
| | 37 | |
|
| 89 | 38 | | RenderTexture rt = RenderTexture.GetTemporary(newWidth, newHeight); |
| 89 | 39 | | rt.filterMode = FilterMode.Point; |
| | 40 | |
|
| 89 | 41 | | RenderTexture.active = rt; |
| 89 | 42 | | Graphics.Blit(source, rt); |
| | 43 | |
|
| 89 | 44 | | Texture2D nTex = new Texture2D(newWidth, newHeight); |
| 89 | 45 | | nTex.ReadPixels(new Rect(0, 0, newWidth, newWidth), 0, 0); |
| 89 | 46 | | nTex.Apply(); |
| | 47 | |
|
| 89 | 48 | | RenderTexture.ReleaseTemporary(rt); |
| 89 | 49 | | RenderTexture.active = null; |
| | 50 | |
|
| 89 | 51 | | return nTex; |
| | 52 | | } |
| | 53 | |
|
| | 54 | | public static Texture2D CopyTexture(Texture2D sourceTexture) |
| | 55 | | { |
| 1 | 56 | | Texture2D texture = new Texture2D(sourceTexture.width, sourceTexture.height, sourceTexture.format, false); |
| 1 | 57 | | Graphics.CopyTexture(sourceTexture, texture); // TODO: does this work in WebGL? |
| 1 | 58 | | return texture; |
| | 59 | | } |
| | 60 | | } |