2013-04-16 34 views
2

我在XAML中设计了一个视图,并且在布局的某个地方有一个Image元素,它将被放入ViewBox,ScrollViewer和Inkcanvas的某个组合中(不确定订单的情况)。目前的早期原型是这样的:如何使WPF图像控件具有与其(BitmapImage)源相同的尺寸?

<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> 

我不能事先知道会是怎样的源图像的尺寸,但我想,以确保图像元素都有其宽度和高度适当的“设置”。原因是我会在图像上绘制(它位于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比例布局转换)。

目标:将ImageWidthHeight属性设置为等于其源图像(通过绑定或其他方式)。

任何想法?

回答

4

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

<Image Stretch="None"/> 
+0

这样做的伎俩。此外,由于Image位于InkCanvas内部,它本身位于ScrollView内部,因此我已经使用InkCanvas尺寸和图像实际尺寸('ActualWidth'和'ActualHeight')之间的ElementProperty绑定,因此我可以直接使用'InkCanvas.Width'。 – heltonbiker

相关问题