Unity texture to XAML Image

Hey all!

I’m trying to load a texture from Unity’s Resources folder and use it to create a XAML Image control. I’m doing this by loading the raw bytes from the Unity texture and sending the bytes in a method like this :

private async void CreateXAMLImage(byte[] bytes, int width, int height, Canvas canvas)
{
    WriteableBitmap bitmap = new WriteableBitmap(width, height);
    Stream stream = bitmap.PixelBuffer.AsStream();
    await stream.WriteAsync(bytes, 0, bytes.Length);

    Image image = new Image();
    image.Source = bitmap;
   
    canvas.Children.Add(image);
}

Here, Canvas is the XAML Canvas, not Unity Canvas.

My issue is that this code generates oddities in the rendered texture. For example, this texture for a red button (white is transparent) :

appears like this in XAML :

In the actual texture I’m using in my project I have 3 single pixel wide lines that rise up from the top of the button, instead of having a red semi-transparent background.

Anyone has an idea on what can be causing this? Is there a better way to add dynamically some images in XAML?

Could it be XAML is using different pixel format, like ARGB instead of RGBA?

Yeah it is BGRA32 so I only need to invert R and B channels. What I use to get the pixel data from the Unity texture is actually GetPixels32 so from there I build a byte array and populate with BGRA32 format. I also invert the lines for each pixel because or some reason, the Image displays the texture upside down

After those two operations I am left with the issue you can see above. I can post more code samples tomorrow but i gotta say when I load this new byte array I just created in a new Texture2D, I can see that it is the original texture upside down so it looks like my byte array is correct? Why would XAML render it differently?

Apparently I need to set the R, G and B channels to 0 when the alpha value is zero or else XAML displays some colors even if the alpha is set to zero. I’m not sure why there are non-zero values in these channels in the first place. I created my original texture with GIMP by creating a transparent background and drawing a circle in the center. There should not be any color in the surrounding pixels.