Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

Correct and fast way to convert from a Windows.UI.Color to System.Numerics.Vector4

How should I convert from Windows.UI.Color to System.Numerics.Vector4?

Colors.White should be Vector4.One, but for the other colors? I need this because Win2D's method CanvasSpriteBatch.DrawFromSpritesheet accept as color parameter a Vector4 (tint).

I think that function could be like:

    private static Vector4 ColorToVector4(Color Color)
    {
        // a, r, g, b purely nominal
        return new Vector4(a, r, g, b);
    }

Upvotes: 0

Views: 939

Answers (2)

Damyan
Damyan

Reputation: 1613

The Vector4 tints used for sprite batches are 4 floats, RGBA. The color in the source bitmap is multiplied by the tint value.

So Vector4.One gives you the same color as in the source bitmap. Vector4(2,1,1,1) will tint it red.

This code will convert a color to a Vector4:

private static Vector4 ToVector4(Color color)
{
    return new Vector4(
        (float)Color.R / 255.0f,
        (float)Color.G / 255.0f,
        (float)Color.B / 255.0f,
        (float)Color.A / 255.0f);
}

(I'll arrange for the Win2D documentation to be updated with this information)

Upvotes: 3

Simo Erkinheimo
Simo Erkinheimo

Reputation: 1397

Sooo... If Vector4.One should be white then I guess Vector4.Zero should be black with zero alpha. Windows.UI.Color seems to hold ARGB values as bytes, each having numeric value between 0-255. So just convert the byte to its numeric value and divide by 255.

Something like

private static Vector4 ColorToVector4(Color Color)
{
  return new Vector4(
                 ColorToFloat(Color.A), 
                 ColorToFloat(Color.R), 
                 ColorToFloat(Color.G), 
                 ColorToFloat(Color.B));
}

private static float ColorToFloat(byte col)
{
  return BitConverter.ToInt16(new byte[1] { col }, 0) / 255f;
}

Upvotes: 0

Related Questions