如何使WPF图像控件具有与其(BitmapImage)源相同的尺寸?

时间:2013-04-16 19:42:04

标签: wpf xaml

我正在设计一个XAML中的View,并且在布局的某个地方有一个Image元素,它将放在ViewBox,ScrollViewer和Inkcanvas的某些组合中(还不确定订单)。目前的早期原型是这样的:

<Window x:Class="InkCanvasTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        x:Name="ThisWindow">


    <DockPanel x:Name="root" DataContext="{Binding ElementName=ThisWindow}">
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" HorizontalAlignment="Center" Margin="0,0,5,0">
            <StackPanel.Resources>
                <Style TargetType="{x:Type Button}" x:Key="EstiloBotão">
                    <Setter Property="Height" Value="40"/>
                    <Setter Property="Width" Value="130" />
                    <Setter Property="Margin" Value="5,5,0,5" />
                </Style>
            </StackPanel.Resources>
            <Button Content="Limpar Alterações" Style="{DynamicResource EstiloBotão}"/>
            <Button Content="Concluir" Style="{DynamicResource EstiloBotão}" Click="Concluir_Click" />
        </StackPanel>
            <!-- Magic Happens Here -->
        <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" PanningMode="Both" Width="752">
            <InkCanvas x:Name="cv" Cursor="Cross" Width="{Binding Width, ElementName=canvas_image}" Height="{Binding Height, ElementName=canvas_image}" >
                <Image x:Name="canvas_image" Stretch="Uniform" Source="C:\Users\helton\Desktop\franjas_binarizadas.png"/>   
            </InkCanvas>
        </ScrollViewer>     

    </DockPanel>
</Window>

我事先无法知道源图像的尺寸,但我想确保Image元素的宽度和高度正确“设置”。原因是我将在图像上绘制(在InkCanvas元素内),然后将结果保存为与源图像大小相同的图像。

目前,我的“保存”方法执行此操作:

    private void Concluir_Click(object sender, RoutedEventArgs e)
    {
        int dWidth = (int)cv.ActualWidth;  // SHOULD BE Width not ActualWidth, but is zero!!!
        int dHeight = (int)cv.ActualHeight;  // Here the same thing
        double dpiX = 96;
        double dpiY = 96;
        RenderTargetBitmap rtb = new RenderTargetBitmap(dWidth, dHeight, dpiX, dpiY, PixelFormats.Pbgra32);
        rtb.Render(cv);

        PngBitmapEncoder pnge = new PngBitmapEncoder();
        pnge.Frames.Add(BitmapFrame.Create(rtb));
        Stream stream = File.Create("franjas_binarizadas_limpas.png");
        pnge.Save(stream);
        stream.Close();
    }

问题:当我尝试阅读“宽度”或“高度”时,它们为零。当我读“ActualHeight”或“ActualWidth”时,有时它们不是我期望的值(由于ScrollView剪辑或ViewBox缩放布局转换)。

目标:将Image的{​​{1}}和Width属性设置为与其源图像相同(通过绑定或其他方式)。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

Stretch属性设置为None。这将使Image控件保持原始位图的大小。

<Image Stretch="None"/>