unity每個(gè)項(xiàng)目都需要使用同一張圖的不同的分辨率 icon,這樣只要一個(gè)最大的分辨率圖片就可以了,需要使用的時(shí)候直接修改圖片的分辨率,用完還可以刪除掉,是不是既方便又可以節(jié)省不少空間。不逼逼直接上腳本
修改圖片分辨的方法:
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;
}
順便這里 給大家寫個(gè)圖片的保存方法:
public static void SaveTexture(Texture2D tex, string toPath)
{
using (var fs = File.OpenWrite(toPath))
{
var bytes = tex.EncodeToPNG();
fs.Write(bytes, 0, bytes.Length);
}
}
再補(bǔ)充個(gè)圖片自動(dòng)壓縮功能
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;
}
這邊是這個(gè)壓縮工具的下載地址: