Search code examples
wpfimagedpi

Use a different image depending on the computer's dpi setting


I have used 16x16 px images in my application, so that I get crisp edges and no automatic resizing at the standard dpi setting of 96.

When the user changes their dpi setting, the images get enlarged, and since the source files are only 16x16, they look naturally bad. Is there a way I can provide multiple images for a particular image source, and the best one will be chosen automatically? For example I provide images with the size of 16x16, 20x20 and 24x24 pixels, when the image's size is 16x16 [wpf units], so I have one perfect match for 96, 120 and 144 dpi?


Solution

  • What best i can think is to set the image source dynamically at run-time based on system's DPI settings. In code-behind you can set dynamically like -

    ImageViewer1.Source = new BitmapImage(new Uri(@"\\myserver\\folder1\\sample.png"));
    

    Listen to this event in your class to get notified about the dpi settings changed of computer - Microsoft.Win32.SystemEvents.DisplaySettingsChanged. Details of it can be found here - System Events

    Also, you can get the system dpi value using the following code -

    float dpiX, dpiY;
    Graphics graphics = this.CreateGraphics();
    dpiX = graphics.DpiX;
    dpiY = graphics.DpiY;
    

    Move this logic to a property and based on the property value, dynamically set the image source.