NGUI Prefab Toolbar缩略图生成

NGUI的Prefab Toolbar可以放一些prefab模板,但是在新版Unity上无法显示缩略图,因此写了个工具为选中的NGUI prefab生成缩略图。

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;

/// <summary>
/// Generate a snapshot for choosed ngui gameobject
/// </summary>
[MenuItem("GameObject/Generate Snapshot", priority = 0)]
public static void GenerateSnapshot()
{
//1.摄像机拍整个画面
//2.截取指定的UI部分
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.");
}
}

//计算NGUI在屏幕中的矩形位置
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, min.y, (max.x - min.x), (max.y - min.y));
//readpixels从左上角开始计算
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对象
RenderTexture rt = new RenderTexture(screenWidth, screenHeight, -1);
camera.targetTexture = rt;
camera.Render();
// 激活这个rt 并从中读取像素
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
// 从RenderTexture.active中读取像素
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;
}
}

这样就可以点击菜单为prefab生成缩略图了,不过要让NGUI显示出来需要把UISnapshotPointEditor中的OnEnable函数改成以下内容,让NGUI默认使用手动截取的缩略图。

1
2
3
4
void OnEnable ()
{
mType = Type.Manual;
}