如何在XAML中获取图像以显示其实际大小?

Edw*_*uay 13 c# wpf xaml image

我有一个27 x 27像素的图像,我在WPF中显示,但它显示大于窗口的大小.

如何让它显示其实际尺寸?

替代文字http://www.deviantsart.com/upload/m20dk6.png

XAML:

<Window x:Class="TestImage23434.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel x:Name="MainStackPanel"/>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System;

namespace TestImage23434
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            TextBlock tb = new TextBlock();
            tb.Text = "above image ";
            MainStackPanel.Children.Add(tb);

            Image img = new Image();
            img.Source = new BitmapImage(new Uri(@"C:\test\circle.png"));
            img.HorizontalAlignment = HorizontalAlignment.Left;
            img.VerticalAlignment = VerticalAlignment.Top;
            MainStackPanel.HorizontalAlignment = HorizontalAlignment.Left;
            MainStackPanel.VerticalAlignment = VerticalAlignment.Top;
            MainStackPanel.Children.Add(img);

            TextBlock tb2 = new TextBlock();
            tb2.Text = "below image";
            MainStackPanel.Children.Add(tb2);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 21

img.Stretch = Stretch.None

默认情况下,Stretch属性的值为Uniform,调整图像大小以填充所有可用空间.

  • 我不认为我曾经以这种方式使用过图像我不得不使用Stretch属性......我忘了它甚至存在. (2认同)
  • 如果设置“ img.Stretch = Stretch.None”,则在图像太大时会出现问题,图像的某些部分将不可见。对此的任何解决方案 (2认同)

Che*_*aoh 6

这些提示都不适合我.一些约束技巧让我走了.

<Image Source="yourPic.png" Stretch="UniformToFill"
Width="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelWidth}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelHeight}" />
Run Code Online (Sandbox Code Playgroud)

您可以将Strech设置为None,但这适用于我的应用程序使用.net 4.5.1.