1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System;
public class UISnapshot : MonoBehaviour { public static int screenWidth = (int)NGUITools.screenSize.x; public static int screenHeight = (int)NGUITools.screenSize.y;
[MenuItem("GameObject/Generate Snapshot", priority = 0)] public static void GenerateSnapshot() { Debug.Log("Generating snapshot..."); GameObject go = Selection.activeObject as GameObject; if (go == null) { Debug.Log("Please choose one prefab!"); return; }
UIRoot uiroot = GameObject.FindObjectOfType<UIRoot>(); GameObject root = uiroot.gameObject; Camera camera = root.transform.Find("Camera").GetComponent<Camera>(); Rect rect = NGUIObjectToRect(go); Texture2D t2d = GetTex(camera, rect); try { string path = "Assets/NGUI/Editor/Preview/" + go.name + ".png"; if (Save2Png(t2d, path)) { UISnapshotPoint sp = go.GetComponent<UISnapshotPoint>(); if (!sp) { sp = go.AddComponent<UISnapshotPoint>(); } sp.thumbnail = t2d; Debug.Log("Generating snapshot success!"); } } catch (Exception) { Debug.LogError("Error occured during generating snapshot."); } }
private static Rect NGUIObjectToRect(GameObject go) { Camera camera = NGUITools.FindCameraForLayer(go.layer); Bounds bounds = NGUIMath.CalculateAbsoluteWidgetBounds(go.transform); Vector3 min = camera.WorldToScreenPoint(bounds.min); Vector3 max = camera.WorldToScreenPoint(bounds.max); return new Rect(min.x, (screenHeight - max.y), (max.x - min.x), (max.y - min.y)); }
public static Texture2D GetTex(Camera camera, Rect rect) { RenderTexture rt = new RenderTexture(screenWidth, screenHeight, -1); camera.targetTexture = rt; camera.Render(); RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); screenShot.ReadPixels(rect, 0, 0); screenShot.Apply(); camera.targetTexture = null; RenderTexture.active = null; GameObject.DestroyImmediate(rt);
return screenShot; }
public static bool Save2Png(Texture2D t2d, string path) { byte[] bytes = t2d.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); return true; } }
|