變換可以讓UI元素扭曲旋轉等,不用改變邏輯的幾何形狀和位置,就像是用放大鏡看物體一樣。
Transform類型的屬性都可以應用變換。
主要分以下三種:RotateTransform、ScaleTransform、TranslateTransform,都繼承自Transform類。
下面建立一個項目TransformTest來實戰一下。
先在螢幕上放一個按鈕:
接下來是給這個按鈕加上旋轉變化。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center" Height="200" Width="400"> <Button.RenderTransform> <RotateTransform Angle="45"></RotateTransform> </Button.RenderTransform> </Button> </Grid>
Angle便是指定旋轉角度,預設的旋轉點是左上方,可以用centerX和centerY來實現。
下面來看看ScaleTransform縮放變換。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center" Height="200" Width="400"> <Button.RenderTransform> <ScaleTransform ScaleX="2" ScaleY="1.5"></ScaleTransform> </Button.RenderTransform> </Button> </Grid>
可以看見這樣就會出現了button的縮放:
同理,可以使用一下代碼實現平移變換。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center" Height="200" Width="400"> <Button.RenderTransform> <TranslateTransform X="100" Y="-200"></TranslateTransform> </Button.RenderTransform> </Button> </Grid>
當然這樣的效果就是:
可以看見button的位置沒有變化,變的是RenderTransform。這一點非常重要。
接下來看一下投射的概念,我們建立一張圖片來做示範。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Image HorizontalAlignment="Center" VerticalAlignment="Center" Height="400" Width="400" Source="頭像.jpg"/> </Grid>
改變其中的Projection屬性:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Image HorizontalAlignment="Center" VerticalAlignment="Center" Height="400" Width="400" Source="頭像.jpg"> <Image.Projection> <PlaneProjection RotationY="45"> </PlaneProjection> </Image.Projection> </Image> </Grid>
這樣我們添加一個定時器就可以實現頭像的3D旋轉展示了。
先用x:name給控制項屬性添加名字:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Image HorizontalAlignment="Center" VerticalAlignment="Center" Height="400" Width="400" Source="頭像.jpg"> <Image.Projection> <PlaneProjection x:Name="pro" RotationY="45"/> </Image.Projection> </Image> </Grid>
然後跳轉到MainPage.xaml.cs後台代碼地區,在下面的OnNavigatedTo方法下添加如下代碼:
protected override void OnNavigatedTo(NavigationEventArgs e) { DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(10); timer.Tick += timer_Tick; timer.Start(); } void timer_Tick(object sender, object e) { pro.RotationY += 1; }
運行項目就可以看見旋轉的頭像了。