Unity使用C#修改图片分辨率
发表于2018-11-21
Unity每个项目都需要使用同一张图的不同的分辨率 icon,对于这种情况只需要考虑留一张最大分辨率的图片即可,然后在使用的时候直接修改图片的分辨率,用完还能删除掉,这样既方便又能节省不少空间。直接给大家上实现脚本。
修改图片分辨的方法:
public static Texture2D ReSetTextureSize(Texture2D tex, int width, int height) { var rendTex = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32); rendTex.Create(); Graphics.SetRenderTarget(rendTex); GL.PushMatrix(); GL.Clear(true, true, Color.clear); GL.PopMatrix(); var mat = new Material(Shader.Find("Unlit/Transparent")); mat.mainTexture = tex; Graphics.SetRenderTarget(rendTex); GL.PushMatrix(); GL.LoadOrtho(); mat.SetPass(0); GL.Begin(GL.QUADS); GL.TexCoord2(0, 0); GL.Vertex3(0, 0, 0); GL.TexCoord2(0, 1); GL.Vertex3(0, 1, 0); GL.TexCoord2(1, 1); GL.Vertex3(1, 1, 0); GL.TexCoord2(1, 0); GL.Vertex3(1, 0, 0); GL.End(); GL.PopMatrix(); var finalTex = new Texture2D(rendTex.width, rendTex.height, TextureFormat.ARGB32, false); RenderTexture.active = rendTex; finalTex.ReadPixels(new Rect(0, 0, finalTex.width, finalTex.height), 0, 0); finalTex.Apply(); return finalTex; }
图片的保存方法:
public static void SaveTexture(Texture2D tex, string toPath) { using (var fs = File.OpenWrite(toPath)) { var bytes = tex.EncodeToPNG(); fs.Write(bytes, 0, bytes.Length); } }
图片自动压缩功能:
public static bool CompressTexture(params string[] texturePath) { var shell = BabySystem.babyFrameWorkAbsolutePath + "TextureTools/"; if (BabySystem.activeBuildTarget == BuildTarget.iOS) shell = shell + "mac/pngquant"; else shell = shell + "win/pngquant.exe"; var strCmdText = "--ext .png " + "--force -- " + string.Join(" ",texturePath); System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = shell; startInfo.Arguments = strCmdText; process.StartInfo = startInfo; process.Start(); process.WaitForExit(); int ExitCode = process.ExitCode; if (ExitCode != 0) { Debug.LogError("Run CMD CompressTexture Failed : "+ExitCode); return false; } return true; }