原创文章如需转载请注明:转载自 脱莫柔Unity3D学习之旅 Unity3D引擎技术交流QQ群:【119706192】本文链接地址: Unity3D NGUI分离RGBA通道

工具脚本

用于拆分图片通道和修改图集shader
借鉴网上多处代码,具体出处已经忘了,反正我也是抄的。
直接上代码:
public class DuanTools_ETC1SeperateRGBA
{static string getPath_NGUIAtlas(){return Application.dataPath + "/Atlas-3";}[MenuItem("DuanTools/ETC1分离RGBA/分离NGUI图片通道")]static void SeperateNGUI_TexturesRGBandAlphaChannel(){Debug.Log("分离Alpha通道 Start.");  string[] paths = Directory.GetFiles(getPath_NGUIAtlas(), "*.*", SearchOption.AllDirectories);foreach (string path in paths){if (!string.IsNullOrEmpty(path) && !IsIgnorePath(path) && IsTextureFile(path) && !IsTextureConverted(path))   //full name{//Debug.Log("path:" + path);SeperateRGBAandlphaChannel(path);}}AssetDatabase.Refresh();ReImportAsset();Debug.Log("分离Alpha通道 Finish.");  }[MenuItem("DuanTools/ETC1分离RGBA/改变NGUI材质")]static void ChangeNGUI_MaterialtoETC1(){//CalculateTexturesAlphaChannelDic();string[] matpaths = Directory.GetFiles(getPath_NGUIAtlas(), "*.mat", SearchOption.AllDirectories);foreach (string matpath in matpaths){string propermatpath = GetRelativeAssetPath(matpath);Material mat = (Material)AssetDatabase.LoadAssetAtPath(propermatpath, typeof(Material));if (mat != null){ChangMaterial(mat, getPath_NGUIAtlas());/*string[] alphatexpaths = GetMaterialTexturesHavingAlphaChannel(mat);if (alphatexpaths.Length == 0){continue;}Debug.Log("Material having texture(s) with Alpha channel : " + propermatpath);foreach (string alphatexpath in alphatexpaths){Debug.Log(alphatexpath + " in " + propermatpath);}*/}else{Debug.LogError("Load material failed : " + matpath);}}Debug.Log("材质改变完成 Finish!");  }#region 分离 RGB & A/// <summary>/// 分离图片通道/// </summary>/// <param name="_texPath"></param>static void SeperateRGBAandlphaChannel(string _texPath){//获得相对路径string assetRelativePath = GetRelativeAssetPath(_texPath);SetTextureReadable(assetRelativePath);Texture2D sourcetex = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(Texture2D)) as Texture2D;  //not just the textures under Resources fileif (!sourcetex){Debug.Log("读取图片失败 : " + assetRelativePath);return;}/*进化版本*/Color[] colors = sourcetex.GetPixels();Texture2D rgbTex2 = new Texture2D(sourcetex.width, sourcetex.height, TextureFormat.RGB24, false);rgbTex2.SetPixels(colors);rgbTex2.Apply();string strPath_RGB = GetRGBTexPath(_texPath);File.WriteAllBytes(strPath_RGB, rgbTex2.EncodeToPNG());ReImport_Addlist(strPath_RGB, rgbTex2.width, rgbTex2.height);Texture2D alphaTex2 = new Texture2D(sourcetex.width , sourcetex.height, TextureFormat.RGB24, false);Color[] alphacolors = new Color[colors.Length];for (int i = 0; i < colors.Length; ++i){alphacolors[i].r = colors[i].a;alphacolors[i].g = colors[i].a;alphacolors[i].b = colors[i].a;}alphaTex2.SetPixels(alphacolors);alphaTex2.Apply();string strPath_Alpha = GetAlphaTexPath(_texPath);File.WriteAllBytes(strPath_Alpha, alphaTex2.EncodeToPNG());ReImport_Addlist(strPath_Alpha, alphaTex2.width, alphaTex2.height); }/// <summary>/// 设置图片为可读格式/// </summary>/// <param name="_relativeAssetPath"></param>static void SetTextureReadable(string _relativeAssetPath){string postfix = GetFilePostfix(_relativeAssetPath);if (postfix == ".dds")    // no need to set .dds file.  Using TextureImporter to .dds file would get casting type error.{return;}TextureImporter ti = (TextureImporter)TextureImporter.GetAtPath(_relativeAssetPath);ti.isReadable = true;AssetDatabase.ImportAsset(_relativeAssetPath);}static Dictionary<string, int[]> ReImportList = new Dictionary<string, int[]>();static void ReImport_Addlist(string path, int width, int height){ReImportList.Add(path, new int[] { width, height });}/// <summary>/// 设置图片格式/// </summary>static void ReImportAsset(){foreach (var item in ReImportList){TextureImporter importer = null;string assetpath = GetRelativeAssetPath(item.Key);try{importer = (TextureImporter)TextureImporter.GetAtPath(assetpath);}catch{Debug.LogError("Load Texture failed: " + assetpath);return;}if (importer == null){Debug.Log("importer null:" + assetpath);return;}importer.textureType = TextureImporterType.Advanced;importer.isReadable = false;  //increase memory cost if readable is true  importer.mipmapEnabled = false;importer.wrapMode = TextureWrapMode.Clamp;importer.anisoLevel = 1;importer.maxTextureSize = Mathf.Max(item.Value[0], item.Value[1]);importer.textureFormat = TextureImporterFormat.ETC_RGB4;importer.compressionQuality = 50;//if (path.Contains("/UI/"))//{//    importer.textureType = TextureImporterType.GUI;//}AssetDatabase.ImportAsset(item.Key);}}#endregion#region 材质static void ChangMaterial(Material _mat,string _texPath){Shader shader;switch (_mat.shader.name){case "Unlit/Transparent Colored":{shader = Shader.Find("Unlit/Transparent Colored ETC1");}break;default: return;}string[] mainPath = Directory.GetFiles(_texPath, _mat.mainTexture.name + "_ETC_RGB.png", SearchOption.AllDirectories);Texture mainTex = AssetDatabase.LoadAssetAtPath(GetRelativeAssetPath(mainPath[0]), typeof(Texture)) as Texture;string[] alphaPath = Directory.GetFiles(_texPath, _mat.mainTexture.name + "_ETC_Alpha.png", SearchOption.AllDirectories);Texture alphaTex = AssetDatabase.LoadAssetAtPath(GetRelativeAssetPath(alphaPath[0]), typeof(Texture)) as Texture;_mat.shader = shader;_mat.SetTexture("_MainTex", mainTex);_mat.SetTexture("_MainTex_A", alphaTex);}#endregion #region Path or 后缀/// <summary>/// 获得相对路径/// </summary>/// <param name="_fullPath"></param>/// <returns></returns>static string GetRelativeAssetPath(string _fullPath){_fullPath = GetRightFormatPath(_fullPath);int idx = _fullPath.IndexOf("Assets");string assetRelativePath = _fullPath.Substring(idx);return assetRelativePath;}/// <summary>/// 转换斜杠/// </summary>/// <param name="_path"></param>/// <returns></returns>static string GetRightFormatPath(string _path){return _path.Replace("\\", "/");}/// <summary>/// 获取文件后缀/// </summary>/// <param name="_filepath"></param>/// <returns></returns>static string GetFilePostfix(string _filepath)   //including '.' eg ".tga", ".dds"{string postfix = "";int idx = _filepath.LastIndexOf('.');if (idx > 0 && idx < _filepath.Length)postfix = _filepath.Substring(idx, _filepath.Length - idx);return postfix;}static bool IsIgnorePath(string _path){return _path.Contains("\\UI\\");}/// <summary>/// 是否为图片/// </summary>/// <param name="_path"></param>/// <returns></returns>static bool IsTextureFile(string _path){string path = _path.ToLower();return path.EndsWith(".psd") || path.EndsWith(".tga") || path.EndsWith(".png") || path.EndsWith(".jpg") || path.EndsWith(".dds") || path.EndsWith(".bmp") || path.EndsWith(".tif") || path.EndsWith(".gif");}/// <summary>/// 是否为自动生成的ETC图片/// </summary>/// <param name="_path"></param>/// <returns></returns>static bool IsTextureConverted(string _path){return _path.Contains("_ETC_RGB.") || _path.Contains("_ETC_Alpha.");}  static string GetRGBTexPath(string _texPath){return GetTexPath(_texPath, "_ETC_RGB.");}static string GetAlphaTexPath(string _texPath){return GetTexPath(_texPath, "_ETC_Alpha.");}static string GetTexPath(string _texPath, string _texRole){string result = _texPath.Replace(".", _texRole);string postfix = GetFilePostfix(_texPath);return result.Replace(postfix, ".png");}#endregion
}

专用的shader

其间夹杂了R通道为0时,自动置灰的shader功能。
Shader "Unlit/Transparent Colored ETC1"
{Properties{_MainTex ("Base (RGB)", 2D) = "black" {}_MainTex_A ("Alpha (A)", 2D) = "white" {}}SubShader{LOD 200Tags{"Queue" = "Transparent""IgnoreProjector" = "True""RenderType" = "Transparent"}Pass{Cull OffLighting OffZWrite OffFog { Mode Off }Offset -1, -1Blend SrcAlpha OneMinusSrcAlphaCGPROGRAM#pragma vertex vert#pragma fragment frag         #include "UnityCG.cginc"sampler2D _MainTex;sampler2D _MainTex_A;float4 _MainTex_ST;struct appdata_t{float4 vertex : POSITION;float2 texcoord : TEXCOORD0;fixed4 color : COLOR;};struct v2f{float4 vertex : SV_POSITION;half2 texcoord : TEXCOORD0;fixed4 color : COLOR;};v2f o;v2f vert (appdata_t v){o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);o.texcoord = v.texcoord;o.color = v.color;return o;}fixed4 frag (v2f IN) : COLOR{fixed4 col;col.rgb = tex2D(_MainTex, IN.texcoord).rgb;col.a = tex2D(_MainTex_A, IN.texcoord).b;if (IN.color.r < 0.001 && IN.color.g > 0.001 && IN.color.b > 0.001)  {  float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));  col.rgb = float3(grey, grey, grey);  }  else  col = col * IN.color;return col;}ENDCG}}SubShader{LOD 100Tags{"Queue" = "Transparent""IgnoreProjector" = "True""RenderType" = "Transparent"}Pass{Cull OffLighting OffZWrite OffFog { Mode Off }Offset -1, -1ColorMask RGBBlend SrcAlpha OneMinusSrcAlphaColorMaterial AmbientAndDiffuseSetTexture [_MainTex]{Combine Texture * Primary}}}
}

另外分别复制Unlit - Transparent Colored 1、2、3,分别创建 Unlit - Transparent Colored  ETC1 1、2、3。并逐一添加A贴图,并读取A贴图的r通道。

UIPanel的拓展

将图集的shader改为ETC1shader后,运行发现,UIPanel选择clipping模式后shader还原了。
解决方案:
UIDrawCall脚本里,找到CreateMaterial()方法修改此处

Unity3D NGUI分离RGBA通道相关推荐

  1. Unity3D NGUI学习(一)血条

    这次来讲讲Unity3D NGUI这个插件的学习,这个插件是收费的,不过去网上可以下载得很多可用版本.用来做用户的交互UI,学习起来比较简单 第一步,导入NGUI包 http://pan.baidu. ...

  2. 转载:【OpenCV入门教程之五】 分离颜色通道多通道图像混合

    本系列文章由@浅墨_毛星云 出品,转载请注明出处. 文章链接: http://blog.csdn.net/poem_qianmo/article/details/21176257 作者:毛星云(浅墨) ...

  3. 【OpenCV入门教程之五】 分离颜色通道多通道图像混合(转)

    本系列文章由@浅墨_毛星云 出品,转载请注明出处. 文章链接: http://blog.csdn.net/poem_qianmo/article/details/21176257 作者:毛星云(浅墨) ...

  4. 【OpenCV C++】分离颜色通道多通道图像混合

    分离颜色通道&多通道图像混合 一.分离颜色通道 <1>split函数详解 <2>merge函数详解 二.多通道图像混合示例程序 本系列文章由@浅墨_毛星云 出品,转载请 ...

  5. OpenCV分离图像通道

    opencv的imread函数读取的灰度图是单通道的. opencv分离图像通道: 源码: Mat img = imread("D:/1.jpg",1);Mat imgR,imgG ...

  6. Unity3d NGUI的使用(二)(UILabel中文字体及可点击的字体)

    用Unity3d NGUI可制作出字体可点击的效果,点击打开网站链接 还有中文字体的显示,可以直接调用系统内置字体,不需要第三方的字体支持 UILabel(Script 参数说明) 第一项字体选项,N ...

  7. 【OpenCV(C++)】分离颜色通道、多通道图像混合

    [OpenCV(C++)]分离颜色通道.多通道图像混合 通道分离:split()函数 通道合并:merge()函数 多通道图像混合实例 为了更好地观察一些图像材料的特征,需要对RGB三个颜色通道的分量 ...

  8. 使用Opencv分离图像通道/合并图像通道

    一. 使用cvSplit将图像的中的通道拆分到单个图像中 1.所需函数:cvSplit 函数功能:将图像的中的通道拆分到单个图像中 函数原型: void cvSplit( const CvArr* s ...

  9. Unity3d NGUI控件知识

    参考:http://forum.exceedu.com/forum/forum.php?mod=viewthread&tid=33091&extra=page%3D1 一.Panel ...

最新文章

  1. 《代码敲不队》第五次作业:项目需求分析改进与系统设计
  2. 2018-2019-2 网络对抗技术 20165324 Exp4:恶意代码分析
  3. 调用PDF的打印命令
  4. 操作系统:第二章 进程管理1 - 进程、线程
  5. java文件传输之文件编码和File类的使用
  6. linux中常用名词解释,科学网—linux中常见名词解释 - 武海丹的博文
  7. jQuery事件对象event的属性和方法
  8. 智林STM32程序源代码的分析和整理03(转帖)
  9. 限时抢购促销海报设计没想法,看这里!眼见的倒计时紧迫感
  10. canvas绘图粒子扩散效果【原创】
  11. i12单双耳切换_“摸一摸”,乐在其中 | 雷柏i100蓝牙TWS耳机,主从切换,可单耳使用,也可双耳使用...
  12. IE11的安装方法和更新补丁
  13. Office在线预览,PPT在线预览,word在线预览,Excel在线预览,PDF在线预览
  14. word里双横线怎么打_word双下划线怎么打出来
  15. python统计数据指标的常见方法
  16. 遇见未来 | 对话叶毓睿:人类文明运行在软件之上(下篇)
  17. 如果《使命召唤》登陆Facebook…
  18. 问题 - GitLab repositories 文件夹权限异常
  19. vue 生命周期 返回不触发_Vue生命周期activated之返回上一页不重新请求数据操作...
  20. 阿里正式启动2021届春季校招!2021Java不死我不倒,好文推荐

热门文章

  1. 最小二乘法(Ordinary Least Squares)
  2. python括号是中文还是英文_Python括号约定
  3. 关于Beyond Compare 4秘钥过期处理方法,百试不爽
  4. 工作十年的数据分析师被炒,没有方向,你根本躲不过中年危机
  5. 阿里短信平台初步使用(无账户可以用支付宝登录)
  6. 程序员们纷纷表示“内牛满面”-VS2010视频共5季
  7. 打印一个N*N的方阵,N为每边字符的个数( 3〈N〈20 ),写出来真是泪牛满面啊。
  8. 水星路由器wan口ip显示0_路由器WAN口获取不到IP地址怎么办?
  9. linux 多wan口 路由器,真假多WAN负载均衡
  10. Arduino 入门学习笔记7 I2C LCD1602液晶显示实验 及 超声波传感器距离检测