lordnoob lordnoob - 1 year ago 76
C# Question

Resizing System.Controls.Image with Nearest Neighbour resizing mode

I'm trying to make a game which uses a pixel art style. I've created my assets and used them as resources, which are added into the window as System.Controls.Image objects.

In the designer, they always turn out too small. As a result, when I resize them, they become somewhat blurred due to some sort of bicubic interpolation being applied onto them.

I have managed to avoid this by avoiding resizing; I resize in the designer to find out what size is appropriate, and then use nearest neighbour resizing on the original image (using an external program) to get the source file to that size. I then update the image in the project and remove any resizing, therefore leaving it at original size, i.e. interpolation-free.

As you can imagine, this is a rather tedious process. I looked into interpolation choices during resizing, but most answers I can find relate to System.Drawing.Image, not System.Controls.Image. I feel like any such solution (if adapted) would be horribly messy and involve multiple (and perhaps unecessary) conversions/casts.

Is there any way to get nearest neighbour resizing on System.Controls.Image?

Answer Source

To set the resize mode, you need to set the RenderOptions.BitmapScalingMode="NearestNeighbor" option for the visual tree. You can set this at the window level.

To address the larger issue, it seems that something is causing your images to be scaled in the first place:

  • Ensure you are setting the Stretch="None" option on the Image control,
  • Ensure that you are using SnapsToDeveicePixels or Layout rounding
  • Lastly if all else fails, explicitly set the width and height of the image.

I have also run into instances where the image file's DPI not being set to (I believe) 90, causes the renderer to apply scaling.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download