我正在開發基於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);
其中,「當前」是在XAML代碼當前圖像的名稱。但我希望它自動發生。在XAML代碼中可能嗎?如果不是,我該如何實現它?
PS:我不是在C#或WPF那麼好。所以如果可能的話,請用外行人的話來解釋。
是否有你使用'Canvas'來包含你的控件的原因?一個'Grid'可以更好地工作,因爲你可以簡單地將圖像的HorizontalAlignment和VerticalAlignment設置爲Center。 – Rachel
@Rachel,是的。我實際上是將我的手座標轉換爲相對於屏幕的位置,然後通過在代碼中設置'Canvas.Left'和'Canvas.Top'屬性,通過縮放的圖像進行平移。我嘗試使用「翻譯變換」,但我無法弄清楚使用該方法。 –