Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch Image inside Canvas

Tags:

wpf

xaml

I would like to have Image inside of Canvas and fit it to the window. When canvas is empty it works fine (canvas is resized within the window), however when I add Image into it, canvas is not fitting to window anymore even though I have Stretch="Uniform" applied to the Image. I illustrate this behavior below. Using the canvas is requirement unfortunately because I draw shapes over it. Any ideas please?

Good

<Window x:Class="ImageCropper.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window3" Height="300" Width="300">
    <Border BorderThickness="3" BorderBrush="Red">
        <Canvas Background="Blue">
        </Canvas>
    </Border>
</Window>

enter image description here

Bad

<Window x:Class="ImageCropper.Window3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window3" Height="300" Width="300">
    <Border BorderThickness="3" BorderBrush="Red">
        <Canvas Background="Blue">
            <Image Source="asd.png" Stretch="Uniform" />
        </Canvas>
    </Border>
</Window>

enter image description here

like image 270
user1121956 Avatar asked Oct 08 '15 15:10

user1121956


1 Answers

I don't think stretch works with canvas very well. See this answer: https://stackoverflow.com/a/6010270/93233

However I was able to get it to work with the following:

<Border BorderThickness="3" BorderBrush="Red">
    <Canvas Background="Blue" Name="canvas1">
        <Image Source="asd.png" Width="{Binding Path=ActualWidth, ElementName=canvas1}" Height="{Binding Path=ActualHeight, ElementName=canvas1}" Stretch="Uniform"/>
    </Canvas>
</Border>
like image 172
Crispy Avatar answered Sep 23 '22 07:09

Crispy