下面是unity自带 16bit 图 的效果,可以看到颜色过度的很不均匀,占用内存 0.5M
如果调成 truecolor 后 颜色过渡很均匀,而内存却占到 1.1 M
讲图片 后缀名改成 .Dither.png 结尾后回到 unity,设置贴图格式为 Truecolor 后,颜色过渡也很均匀,而且内存只占了 0.5M
以下代码来至 keijiro 的 github:unity-dither4444
using UnityEngine;
using UnityEditor;
using System.Collections; class TextureModifier : AssetPostprocessor
{
void OnPreprocessTexture()
{
var importer = (assetImporter as TextureImporter); importer.textureType = TextureImporterType.GUI; if (assetPath.EndsWith ("Dither.png")) {
importer.textureFormat = TextureImporterFormat.RGBA32;
}
} void OnPostprocessTexture (Texture2D texture)
{
if (!assetPath.EndsWith ("Dither.png")) {
return;
} var texw = texture.width;
var texh = texture.height; var pixels = texture.GetPixels ();
var offs = ; var k1Per15 = 1.0f / 15.0f;
var k1Per16 = 1.0f / 16.0f;
var k3Per16 = 3.0f / 16.0f;
var k5Per16 = 5.0f / 16.0f;
var k7Per16 = 7.0f / 16.0f; for (var y = ; y < texh; y++) {
for (var x = ; x < texw; x++) {
float a = pixels [offs].a;
float r = pixels [offs].r;
float g = pixels [offs].g;
float b = pixels [offs].b; var a2 = Mathf.Clamp01 (Mathf.Floor (a * ) * k1Per15);
var r2 = Mathf.Clamp01 (Mathf.Floor (r * ) * k1Per15);
var g2 = Mathf.Clamp01 (Mathf.Floor (g * ) * k1Per15);
var b2 = Mathf.Clamp01 (Mathf.Floor (b * ) * k1Per15); var ae = a - a2;
var re = r - r2;
var ge = g - g2;
var be = b - b2; pixels [offs].a = a2;
pixels [offs].r = r2;
pixels [offs].g = g2;
pixels [offs].b = b2; var n1 = offs + ;
var n2 = offs + texw - ;
var n3 = offs + texw;
var n4 = offs + texw + ; if (x < texw - ) {
pixels [n1].a += ae * k7Per16;
pixels [n1].r += re * k7Per16;
pixels [n1].g += ge * k7Per16;
pixels [n1].b += be * k7Per16;
} if (y < texh - ) {
pixels [n3].a += ae * k5Per16;
pixels [n3].r += re * k5Per16;
pixels [n3].g += ge * k5Per16;
pixels [n3].b += be * k5Per16; if (x > ) {
pixels [n2].a += ae * k3Per16;
pixels [n2].r += re * k3Per16;
pixels [n2].g += ge * k3Per16;
pixels [n2].b += be * k3Per16;
} if (x < texw - ) {
pixels [n4].a += ae * k1Per16;
pixels [n4].r += re * k1Per16;
pixels [n4].g += ge * k1Per16;
pixels [n4].b += be * k1Per16;
}
} offs++;
}
} texture.SetPixels (pixels);
EditorUtility.CompressTexture (texture, TextureFormat.RGBA4444, TextureCompressionQuality.Best);
}
}