Search code examples
c#slimdx

Fit image to ShaderResourceView and preserve aspect ratio


I'm loading an image into a ShaderResourceView to be used as a background image. This is what I'm currently using:

ShaderResourceView.FromFile(_device, imagepath);

It loads the image into the background, but it stretches both dimensions without regard to the aspect ratio. Is there a way to load an image into the background and preserve aspect ratio?


Solution

  • Ideally ShaderResourceView would provide a setting to automatically respect the image aspect, but below is the next best option.

    An existing post on SO fits the image to a specified size, then pads any extra space with whitespace and creates a new image. Link: https://stackoverflow.com/a/2001462/978622

    Another post shows how to easily convert from an Image to a bytearray, which is one of the types ShaderResourceView can create a shader from. Link: https://stackoverflow.com/a/3801289/978622

    My code which puts it all together:

    var original = Image.FromFile(path);
    Image resized = FixedSize(original, actualWidth, actualHeight);
    var byteImage = ImageToByteArray(resized);
    var srv = ShaderResourceView.FromMemory(_device, byteImage);