【发布时间】:2012-10-03 14:42:05
【问题描述】:
我正在使用 Kinect 开发基于手势的图像查看器。我正在使用以下 XAML 代码在画布上显示图像。
<Canvas Background="Transparent" Height="732" VerticalAlignment="Top">
<Image x:Name="next" Source="{Binding NextPicture}" StretchDirection="Both" Stretch="Uniform" ClipToBounds="True" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality" RenderTransformOrigin="0.5,0.5" Opacity="0" Grid.ColumnSpan="2" Height="732" Width="Auto" HorizontalAlignment="Center" />
<Image x:Name="previous" Source="{Binding PreviousPicture}" StretchDirection="Both" Stretch="Uniform" ClipToBounds="True" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality" RenderTransformOrigin="0.5,0.5" Opacity="0" Grid.ColumnSpan="2" Height="732" Width="Auto" HorizontalAlignment="Center" />
<Image x:Name="current" Source="{Binding Picture}" StretchDirection="Both" Stretch="Uniform" ClipToBounds="True" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality" RenderTransformOrigin="0.5,0.5" Grid.ColumnSpan="2" Height="732" Width="Auto" HorizontalAlignment="Center" />
</Canvas>
这是在后面运行的代码:
/// <summary>
/// Gets the previous image displayed.
/// </summary>
public BitmapImage PreviousPicture { get; private set; }
/// <summary>
/// Gets the current image to be displayed.
/// </summary>
public BitmapImage Picture { get; private set; }
/// <summary>
/// Gets the next image displayed.
/// </summary>
public BitmapImage NextPicture { get; private set; }
每次识别手势时,属性都会改变如下:
// Setup corresponding picture if pictures are available.
this.PreviousPicture = this.Picture;
this.Picture = this.NextPicture;
this.NextPicture = LoadPicture(Index + 1);
// Notify world of change to Index and Picture.
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("PreviousPicture"));
this.PropertyChanged(this, new PropertyChangedEventArgs("Picture"));
this.PropertyChanged(this, new PropertyChangedEventArgs("NextPicture"));
}
但问题是,我在画布上显示的图像随机向左或向右对齐。它们的纵横比有时也会发生变化。我想要的是,图像应该以其原始纵横比显示在画布的中心。有人可以在这方面帮助我吗?
另外,我可以使用 C# 代码将图像设置为中心,如下所示:
Canvas.SetLeft(current, (1249 - current.ActualWidth) / 2);
Canvas.SetTop(current, 0);
其中,'current' 是 XAML 代码中当前图像的名称。但我希望它自动发生。 XAML 代码中是否有可能?如果没有,我该如何实现?
PS:我不太擅长 C# 或 WPF。所以请尽可能通俗地解释一下。
【问题讨论】:
-
您使用
Canvas来包含您的控件是否有原因?Grid会更好,因为您可以简单地将图像的HorizontalAlignment和VerticalAlignment设置为Center。 -
@Rachel,是的。我实际上是将我的手坐标转换为相对于屏幕的位置,然后通过在我的代码中设置“Canvas.Left”和“Canvas.Top”属性来平移缩放图像。我尝试使用“翻译转换”,但我找不到使用它的方法。