WPF: How to display an image at its original size?

后端 未结 5 1001
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 13:05

I have a problem with displaying images in WPF.

Here\'s my code:

相关标签:
5条回答
  • 2020-12-02 13:16

    If you want to display the image with original size, but don't know the image size, I think the best way is to set the image as background of UIElement. Like this:

        <Button>
            <Button.Background>
                <ImageBrush ImageSource="/images/user_add.png" Stretch="None"/>
            </Button.Background>
        </Button>
    
    0 讨论(0)
  • 2020-12-02 13:21

    Adding to Paya's answer: to compensate WPF's attempt to adapt to the monitors resolution you should be able to set the Width and Height to the file's original dimensions and use Stretch="Fill". This worked for me.

    0 讨论(0)
  • 2020-12-02 13:22
    <Image Source="Images/Background.png" UseLayoutRounding="True" SnapsToDevicePixels="True" Width="600" Height="800" Stretch="Fill" />
    

    This one works for me, for an image with 600x800 pixels and 96dpi.

    @rishad2m8 If size is unknown one can detect the size first with https://msdn.microsoft.com/en-us/library/system.drawing.image.size(v=vs.110).aspx I'd guess.

    0 讨论(0)
  • 2020-12-02 13:23

    Try not specifying width or height, use it like this instead:

    <Image Source="/images/user_add.png" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
    
    0 讨论(0)
  • 2020-12-02 13:28

    Here is a similar question. Generally setting Stretch="None" is enough.

    It is also very important what DPI has the image set in metadata. It took me quite a while before figuring out that if the image's DPI is different from the monitor's DPI (usually 96), WPF will automatically resize the image, as it tries to be DPI-independent.


    EDIT

    The MSDN link is broken, here is the new link: MSDN Blog - Blurry Bitmaps. Let's keep the old link around to be used for archive.org, in case the new link stops working also.

    0 讨论(0)
提交回复
热议问题