【发布时间】:2013-04-16 19:42:03
【问题描述】:
我正在用 XAML 设计一个视图,在布局的某个地方有一个 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 元素的 Width 和 Height 正确“设置”。原因是我将在图像(位于 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 的Width 和Height 属性设置为与其源图像相同(通过绑定或其他方式)。
有什么想法吗?
【问题讨论】: