Using transparent images as TextureSource (Unity)
Posted: 17 Oct 2013, 10:16
After release of the NoesisGUI 1.1 we was very happy to start using the TextureSource feature. But it has issue with the tranparent textures:
Converter usage example code (C#):
We asked the NoesisGUI team about it and they respond kindly:
So, the NoesisGUI require textures in premultiplied alpha format to render it correctly. Here is the C# code of texture converter class written for our game project. We decide to open source of this converter to support the NoesisGUI community!"We have been investigating this issue and found an explanation. Problem is that Unity doesn't use premultiply alpha (blogs.msdn.com/b/shawnhar/archive/2009/11/06/premultiplied-alpha.aspx) and NoesisGUI pipeline is entirely based in premultiply alpha. Premultiply alpha is the correct way to do the things.
Ideally the conversion from straight alpha to premultiplied alpha should be done at texture import time (as we do in Noesis), but there is no option to active it in Unity. The solution for you is doing in by hand. You have to multiply each color channel by the alpha channel."
Code: Select all
using UnityEngine;
public static class TextureConverter
{
public static Texture2D ConvertToPremultipliedAlpha(Texture2D source)
{
Color[] srcColors = source.GetPixels();
Color[] dstColors = new Color[srcColors.Length];
for (int i = 0; i < srcColors.Length; i++)
{
Color srcColor = srcColors[i];
float a = srcColor.a;
dstColors[i] = new Color(srcColor.r * a, srcColor.g * a, srcColor.b * a, a);
}
Texture2D result = new Texture2D(source.width, source.height, TextureFormat.ARGB32, false);
result.SetPixels(dstColors);
result.Apply();
return result;
}
}
Code: Select all
// texture is variable representing Texture2D
var convertedTexture = TextureConverter.ConvertToPremultipliedAlpha(texture);
// now you can use this texture in TextureSource
var textureSource = new TextureSource(convertedTexture);