How can I get images in XAML to display as their actual size?
I have a 27 x 开发者_StackOverflow27 pixel image that I am displaying in WPF but it displays larger than the size of the window.
How can I get it to display its actual size?
alt text 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>
Code Behind:
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);
}
}
}
img.Stretch = Stretch.None
By default, the Stretch property has a value of Uniform
, which resizes the image to fill all available space.
None of these tips were working for me. Some binding tricks is what got me going.
<Image Source="yourPic.png" Stretch="UniformToFill"
Width="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelWidth}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelHeight}" />
You could probably set Strech to None but this worked for my app using .net 4.5.1.
img.HorizontalAlignment = HorizontalAlignment.Left;
img.VerticalAlignment = VerticalAlignment.Top;
img.Stretch = Stretch.None;
The StackPanel will stretch to fill/overflow whatever container it's in unless its size is specified. Since you aren't setting margins or alignments on anything, the default behavior for everything is Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
, or simply put "Stretch to fill". Aligning/positioning your elements will fix this issue.
EDIT: Added img.Stretch = Stretch.None;
, also I built a sample app and tested it... it works.
It could also be your image's DPI property in its metadata. It should be 96. https://stackoverflow.com/a/4965404/659326
精彩评论