tags:

views:

159

answers:

2

I have a 27 x 27 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

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);
        }
    }
}
+1  A: 
img.HorizontalAlignment = HorizontalAlignment.Left;
img.VerticalAlignment = VerticalAlignment.Top;
img.Strecth = 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.

EDIT: Added img.Strecth = Stretch.None;, also I built a sample app and tested it... it works.

md5sum
How does the alignment affect the size of the displayed image?
dtb
The standard alignment is `Stretch`, which *does* affect the size.
Heinzi
Edited answer to explain.
md5sum
I tried that but it still expands to the size of its possible area. I tried putting these settings on the StackPanel as well but it still expands.
Edward Tanguay
I reposted the code with those changes.
Edward Tanguay
@Heinzi - Thx, was wondering why it got a downvote until I saw your edit... :D
md5sum
+5  A: 

img.Stretch = Stretch.None

By default, the Stretch property has a value of Uniform, which resizes the image to fill all available space.

Heinzi
I don't think I've ever used an image in such a way I've had to USE the Stretch property... I forgot it even existed.
md5sum
Indeed. I'm also quite surprised about this choice of default value...
Heinzi