unity-UI-RawImage-SetNativeSize
2017-05-26 本文已影响0人
thrt520
在untiy ui的图片格式选择问题上我们一般会选择sprite,但是在遇到大尺寸图片时sprite会占用非常大的存储空间,增大包体,如果你把图片格式改为texture会发现图片大小减少很多,但是Image不能选择texture资源,这时可以选择RawImage代替Image,RawImage可以使用texture资源,但是RawImage使用SetNativeSize时发现由于untiy会对导入的图片资源进行处理,如果选择texture格式会强行将分辨率改为2的次方大小的,RawImage设置为初始尺寸后发现会按照导入后图片的分辨率来设置而不是根据图片的原始尺寸设置大小,由于美术出图时很少会按照2的次方大小来出图,所有还需要切到windows中查看图片分辨率,再去设置(写好长,手好酸,好难过,不想写了,代码很简单,也不需要注释),身为一个懒比,抵制这种操作,下面是代码:
///rawImage拓展方法
//setActiveSize
[MenuItem("CONTEXT/RawImage/SetNativeSize")]
public static void SetRawImageNativeSize(){
GameObject[] gos = Selection.gameObjects;
//Debug.Log ("go name:" + gos [0].name);
System.DateTime startTime = System.DateTime.Now;
for (int i = 0; i < gos.Length; i++) {
GameObject go = gos [i];
Texture t = go.GetComponent<RawImage> ().texture;
if (t == null) {
Debug.LogError ("raw image 未选择图片");
return;
} else {
string path = AssetDatabase.GetAssetPath (t);
TextureImporter textureimporter = AssetImporter.GetAtPath (path) as TextureImporter;
TextureImporterType type = textureimporter.textureType;
textureimporter.textureType = TextureImporterType.Sprite;
AssetDatabase.ImportAsset(path);
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite> (path);
Rect rect = sprite.rect;
textureimporter.textureType = type;
AssetDatabase.ImportAsset (path);
(go.transform as RectTransform).sizeDelta = new Vector2(rect.width , rect.height);
}
}
System.DateTime endtime = System.DateTime.Now;
double time = (endtime - startTime).TotalSeconds ;
Debug.Log ("total seconds:" + time.ToString ("f2") + "s");
}